Using a variable to refer to another variable in R?

本小妞迷上赌 提交于 2019-12-13 07:38:52

问题


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=""))))
}

回答1:


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))

Here the results are stored in a named list. You can get them out with CombineResult$A or CombineResult[["A"]]



来源:https://stackoverflow.com/questions/33614152/using-a-variable-to-refer-to-another-variable-in-r

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