R for loop with characters list

核能气质少年 提交于 2019-12-13 20:19:08

问题


I have a df such as:

name <- rep(c("a","b","c"),5)
QV.low <- runif(15, 2, 5)
QV.med <- runif(15, 5.0, 7.5)
QV.high <- runif(15, 7.5, 10)
df <-  as.data.frame(cbind(name, QV.low, QV.med,QV.high))

and a list of names:

name.list <- c("a","b")

I want to do an operation, eg:

df %>% 
    subset(name %in% name.list) %>%
    summarise(.,sum = sum(QV.low))

but I want to for each QV. variable via a loop.

I tried:

QV.list <- c("QV.low", "QV.med", "QV.high")
for(qv in 1:length(QV.list)){
    QV <- noquote(QV.list[qv])
    print(QV)
    df %>% 
        subset(name %in% name.list) %>%
        summarise(.,sum = sum(QV))
}

But it does not work.

How can I "extract" the character value from the QV.list in order to use it as df variable later?


回答1:


You need to have at least 3 different names in namecol otherwise namecol %in% name.list1 is useless. If there's no filter and no pipe, there's no need for a loop. A simple colSums(df[,-1]) will do the job.

library(tidyverse)

QV.low <- runif(10, 2, 5)
QV.med <- runif(10, 5.0, 7.5)
QV.high <- runif(10, 7.5, 10)
namecol <- sample(c("a","b", "c"), 10, replace = T)
df <-  data.frame(namecol, QV.low, QV.med,QV.high)
df
name.list1  <- c("a","b") # select some names

QV.list <- c("QV.low", "QV.med", "QV.high")

for(i in QV.list){
  QV <- noquote(i)
  print(QV)
  qv <- sym(i)
  print(df %>% 
    filter(namecol %in% name.list1) %>%
    summarise(sum = sum(!!qv)))
}

will give you

[1] QV.low
     sum
1 29.093
[1] QV.med
       sum
1 61.07034
[1] QV.high
       sum
1 86.02611



回答2:


if I understood your problem you can resolve with this:

for( name in names(df)){
  df[,name]
  ....
  df %>% summarise(.,sum = sum(df[,name]))
}


来源:https://stackoverflow.com/questions/55162067/r-for-loop-with-characters-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!