如何在R语言中替换dataframe指定行的数值?
解决DataFrame指定行的映射值替换问题
原始数据
df = data.frame(row.names = c("IL6", "AS-1", "KPMG", "DS55", "CD44", "Type"), Class1 = c(1, 19, 18, 11, 2, "ACC"), Class2 = c(3, 12, 20, 9, 12, "ACC"), Class3 = c(6, 5, 9, 16, 9, "BRCA"), Class4 = c(3, 9, 18, 15, 14, "BRCA"), Class5 = c(4, 20, 19, 19, 16, "BRCA"), Class6 = c(3, 12, 20, 9, 12, "SRCA"), Class7 = c(6, 5, 9, 16, 9, "SRCA"), Class8 = c(3, 9, 18, 15, 14, "GBM"))
需求
根据映射规则 ACC=1, BRCA=2, SRCA=3, GBM=4,替换行名为Type的所有列值。
报错情况
尝试以下代码时出现错误:
# mapping values mapping <- c("ACC" = "1", "BRCA" = "2", "SRCA" = "3", "GBM" = "4") # Replace the values in the 'Type' row df["Type", ] <- mapping[df["Type", ]]
错误信息:
Error in mapping[df["Type", ]]: invalid subscript type 'list'
问题原因
df["Type", ]返回的是1行的DataFrame,属于列表(list)类型,而向量mapping的索引只能接受原子向量(如字符向量),因此触发类型不匹配的错误。
解决方案
将df["Type", ]转换为字符向量后再进行映射替换,有两种常用方式:
方法1:使用as.character()转换
mapping <- c("ACC" = "1", "BRCA" = "2", "SRCA" = "3", "GBM" = "4") df["Type", ] <- mapping[as.character(df["Type", ])]
方法2:使用unlist()转换
mapping <- c("ACC" = "1", "BRCA" = "2", "SRCA" = "3", "GBM" = "4") df["Type", ] <- mapping[unlist(df["Type", ])]
验证结果
执行后得到期望的输出:
output <- data.frame(row.names = c("IL6", "AS-1", "KPMG", "DS55", "CD44", "Type"), Class1 = c(1, 19, 18, 11, 2, "1"), Class2 = c(3, 12, 20, 9, 12, "1"), Class3 = c(6, 5, 9, 16, 9, "2"), Class4 = c(3, 9, 18, 15, 14, "2"), Class5 = c(4, 20, 19, 19, 16, "2"), Class6 = c(3, 12, 20, 9, 12, "3"), Class7 = c(6, 5, 9, 16, 9, "3"), Class8 = c(3, 9, 18, 15, 14, "4"))
内容的提问来源于stack exchange,提问作者nicholaspooran
相关产品推荐
相关产品推荐

