使用变量来引用 R 中的另一个变量? [英] Using a variable to refer to another variable in R?
问题描述
我正在尝试在 R 中运行for"循环来分析多个变量.我有一个带有列名(AppleTag1"、AppleTag2"、CherryTag1"、CherryTag2"....)的数据集(DataSet").该循环是针对ColumnName"中列出的每个唯一列名称比较Tag1"和Tag2"列,并从两列中获取具有唯一值的向量.我的问题是如何将粘贴函数的结果称为变量.我知道用于收集唯一结果的第一个过去函数可以用align()"修复.然而,另外两个呢?如何确保 R 将 paste() 结果DataSet$AppleTag1"分析为变量而不是字符串".现在,我得到了一个包含DataSet$AppleTag1、DataSet$AppleTag2"的CombineResult_XXX"列表,但我想要的是它测试这两列中的内容并得到类似123、213、141、232"的内容.感谢您的帮助.
I am trying to run a "for" loop in R to analyze multiple variables. I have a data set ("DataSet") with column names ("AppleTag1", "AppleTag2", "CherryTag1", "CherryTag2"....). The loop is to compare "Tag1" with "Tag2" columns for each unique column name listed in "ColumnName" and obtain a vector with unique values from both columns. My question is how do I refer to the result of a paste function as a variable. I know the first past function used to collect the unique results can be fixed with "align()". However, what about the other two? How can I make sure R analyzes the paste() result "DataSet$AppleTag1" as a variable and not as a "string". Right now, I get a list of "CombineResult_XXX" with "DataSet$AppleTag1, DataSet$AppleTag2," yet I want is for it to test what is inside these two columns and get something like "123, 213, 141, 232". Thank you for your help.
ColumnName <- c("Apple","Cherry","Bubble","Killer","Fat","Glass","Comp","Key")
NameTag <- c(A,B,C,D,E,F,G,H,I,J)
for (i in 1:10) {
paste("CombineResult_",NameTag[i],sep="") <- unique(c(
as.vector(paste("DataSet$",ColumnName[i],"Tag1", sep="")),
as.vector(paste("DataSet$",ColumnName[i],"Tag2", sep=""))))
}
推荐答案
您不能将 $
与字符串一起用于列名.如果要使用字符串进行子集化,请使用 [[
表示法.也许这样的事情会更好.
You can't use $
with strings for column names. If you want to subset with strings, use the [[
notation. Maybe something like this would be better.
ColumnName <- c("Apple", "Cherry", "Bubble", "Killer", "Fat", "Glass", "Comp", "Key")
NameTag <- c("A","B","C","D","E","F","G","H","I","J")
CombineResult <- lapply(ColumnNames, function(x) {
unique(c(
DataSet[[paste0(x,"Tag1")]],
DataSet[[paste0(x,"Tag2")]]
))
})
names(CombineResult) <- NameTag(seq_along(CombineResult))
这里的结果存储在一个命名列表中.你可以用 CombineResult$A
或 CombineResult[["A"]]
Here the results are stored in a named list. You can get them out with CombineResult$A
or CombineResult[["A"]]
这篇关于使用变量来引用 R 中的另一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!