TeYaP
TeYaP

Reputation: 323

R for loop with characters list

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?

Upvotes: 0

Views: 1684

Answers (2)

LAP
LAP

Reputation: 6685

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

Upvotes: 2

LorNap
LorNap

Reputation: 51

if I understood your problem you can resolve with this:

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

Upvotes: 0

Related Questions