【问题标题】:Recode multiple columns based on grep column label outcome in R根据 R 中的 grep 列标签结果重新编码多列
【发布时间】:2017-02-23 18:43:29
【问题描述】:

我有多个我想在 R 中重新编码的列(是 - 1,否 - 0,Null - NA)。这些列都包含单词“标志”作为列标签的一部分,我有大约 60这些列重新编码。我也有以其他词结尾的列名,我希望应用相同的逻辑并分批重新编码。

这是我的数据框的示例。我将它作为 .csv 文件导入到 RStudio 并设置 stringsAsFactors = F

> test <- data.frame(ID = c("86224AA8", "911D8EF", "959661A0", "A4935669", "9A77218A", "19884814",  "017E5338", "6DBCFBB"), CreatedDate = c("18/11/2015", "18/12/2015", "15/11/2015", "13/11/2015", "08/09/2015", "07/11/2013", "18/11/2015", "18/11/2015"), V2Flag = c("No", "No", "No", "No", "Yes", "Yes", "NULL", "Yes"), V3Flag = c("Yes", "NULL", "Yes", "No", "Yes", "Yes", "NULL", "Yes"), V4Flag = c("No", "NULL", "Yes", "No", "Yes", "No", "NULL", "No"))
> test
         ID CreatedDate V2Flag V3Flag V4Flag
1 86224AA8  18/11/2015     No    Yes     No
2  911D8EF  18/12/2015     No   NULL   NULL
3 959661A0  15/11/2015     No    Yes    Yes
4 A4935669  13/11/2015     No     No     No
5 9A77218A  08/09/2015    Yes    Yes    Yes
6 19884814  07/11/2013    Yes    Yes     No
7 017E5338  18/11/2015   NULL   NULL   NULL
8  6DBCFBB  18/11/2015    Yes    Yes     No

这是我尝试在 R 中重新编码以“标志”结尾的列名中的是/否响应。

> test[, grepl("Flag", names(test)) == 'No'] <- 0 
> test[, grepl("Flag", names(test)) == 'Yes'] <- 1 
> test[, grepl("Flag", names(test)) == 'NULL'] <- NA

这些行在 R 中运行良好并且没有返回任何错误。但是,如全局环境所示,这些列仍然不会将 Yes/No 输出显示为 1/0。

如果我首先使用“grepl”对我的数据集进行子集化,请将选定的以“Flag”结尾的列存储在单独的数据框中。我在重新编码二进制响应时没有任何问题。

您能否建议我的代码中出了什么问题,以及如何根据列的名称选择列并重新编码(不设置我的数据框的子集)?

谢谢!

【问题讨论】:

  • 谢谢!它工作正常 - 我将 test[test[,1:5] == "No"] = 0 替换为 test[test[,grepl("Flag", names(test) == "No"] = 0 等,但是无法产生相同的结果。在我的数据框中,这些列并不相邻,这就是为什么我想使用 grepl 来定位这些以相同单词结尾的列......为什么 grepl 似乎不起作用?

标签: r str-replace grepl recode


【解决方案1】:

这是一种重新编码No 的方法。为其他人重复。

#Convert columns 3, 4, and 5 to character
#This may or may not be necessary for your actual data
test[,3:5] = lapply(test[,3:5], as.character)

#Obtain column numbers where 'Flag' is present
ind1 = which(grepl("Flag", names(test)))

#Obtain indices of where the values are 'No'
ind2 = which(test == "No", arr.ind = TRUE)

#Keep only those values in ind2 where column numbers match with ind1
ind2 = ind2[ind2[,2] %in% ind1,]

#Recode values to zero
test[ind2] = 0

【讨论】:

    猜你喜欢
    • 2020-01-26
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多