简体   繁体   中英

Loop through specific columns in dataframe

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

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]

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM