0

I have a dataframe that I'm trying to loop through, printing out the values from each dataframe... I'm new to R and am more familiar with python and javascript so I'm gonna pseudo-code what I'm trying to say here:

df <- read.table(text="
              a     b    c    d     e      f       g
              1     5    6    7     3      4       7
              3     2    8    4     1      9       4
              6     5    2    5     4      6       1
         ",header=TRUE,stringsAsFactors = FALSE)

my javascript mentality...(I only want to select from columns 4 and on):

for (i = 3; i < df.length; i++) {
     console.log(i)
}

and it would return to me

              d     e      f       g
              7     3      4       7
              4     1      9       4
              5     4      6       1

to understand this better, I'm making a dashboard where when I hover over certain data points only values from certain columns are being displayed in a tooltip, which is why i still need to keep the original dataframe without shortening it, yet write an algorithm that will return values from specific columns in the dataframe just for the tooltip

3 Answers 3

3

Here are two different ways two subset a dataframe:

# by column numbers
df[, 4:7]

# by column names
names <- c("d", "e", "f", "g")
df[names]
Sign up to request clarification or add additional context in comments.

7 Comments

i need to subset everything after the 3rd row. how do i do that? I tried df[, 4:] and df[, 4:nrow(df)] with no luck
try df[, 4:ncol(df)] or df[, 4:length(df)]. Is this what you are looking for?
you only don't need the first 3. you can also do df[,-(1:3)]
Onyambu's worked but it actually turns out I also need to drop the last two, so how do I add that in now without selecting specific columns? Reason being is because the number of columns between the 4th up until the last two may vary...
@Onyambu answer does the exact same subsetting as the solution that I supplied based on your reproducible example. drop <- -c((1:3), c(dim(df)[2], dim(df)[2]-1)); df[, drop]
|
0

Try this: df[,c(3,4,5,6)]

And check out this link: https://dzone.com/articles/learn-r-how-extract-rows

I'm not sure if this is what you are asking.

1 Comment

almost, I need everything after the 3rd column. I don't want to specify exactly which ones
0

You can run a loop over with a conditional to loop:

for (column in dataFrame) {
if(column %% 2 == 0){
for (entry in rawdata[,column]) {
#run your code here, it will impact ever second column
  }
 }
}

Change the 0 to a 1 in order to do it for every odd column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.