R for循环与字符列表 [英] R for loop with characters list
本文介绍了R for循环与字符列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个df,例如:
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))
和名称列表:
name.list <- c("a","b")
我想做一个手术,例如:
I want to do an operation, eg:
df %>%
subset(name %in% name.list) %>%
summarise(.,sum = sum(QV.low))
但是我想通过循环为每个QV.
变量.
but I want to for each QV.
variable via a loop.
我尝试过:
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))
}
但是它不起作用.
如何从QV.list
中提取"字符值,以便以后将其用作df变量?
How can I "extract" the character value from the QV.list
in order to use it as df variable later?
推荐答案
namecol
中至少需要3个不同的名称,否则namecol %in% name.list1
是没有用的.如果没有过滤器也没有管道,则无需循环.一个简单的colSums(df[,-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)))
}
会给你
[1] QV.low
sum
1 29.093
[1] QV.med
sum
1 61.07034
[1] QV.high
sum
1 86.02611
这篇关于R for循环与字符列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文