【问题标题】:Replace Multiple Values Using Rowname as Identifier使用行名作为标识符替换多个值
【发布时间】:2018-06-26 14:17:21
【问题描述】:

我一直在尝试用行名替换列中的多个值。在我的实际数据中,它们代表了一种主观测试,在该特定点被记录为阳性或阴性。我必须在我的数据框中重新分类它,我所要做的就是样本 ID,它们是行名。

与其手动更改每个特定值,我想知道是否有一种方法可以一次执行多个值。我看了this question。我试过这个,

        dat <- structure(list(A = structure(c(2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L,2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L), .Label = c("1", "0"), class = "factor"),B = structure(c(1L,1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,1L, 1L, 1L, 1L, 2L, 1L, 1L), .Label = c("0", "1"), class = "factor"),C = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L), .Label = c("nd","0", "1"), class = "factor"),D = structure(c(1L, 1L, 1L,2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L,2L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor"),E = structure(c(1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0","1"), class = "factor")),.Names = c("A", "B", "C", "D", "E"), class = "data.frame", row.names = c(NA, 24L))

        dat$result <- as.integer(rowSums(dat[,1:5] == "1")> 0)
        dn <- c("1","5","7","10","14","15","16")
        dat$result[dn] <- "3"

请有人帮我解决这个问题。

【问题讨论】:

  • dat3 未定义。我认为应该是dat,但我无法编辑它
  • @SeGa 谢谢,我已经编辑过了

标签: r dataframe data-manipulation


【解决方案1】:

dn 必须是数字,而不是字符。

当你以 dn 作为字符运行命令时,你只会得到 NA 值:

dat$result[dn]
# [1] NA NA NA NA NA NA NA

如果您将dn 更改为数字,您将获得正确的值:

dat$result[as.numeric(dn)]
# [1] 0 1 0 1 0 1 0

然后您可以像这样分配新值:

dat$result[as.numeric(dn)] <- 3
dat$result
# [1] 3 0 1 1 3 1 3 1 0 3 0 1 1 3 3 3 1 1 1 0 0 1 0 1

这不会按 row.names 而是按索引过滤 data.frame,但由于它是一个有序序列,您可以只使用这些索引进行转换。还是需要根据row.names进行匹配?


要按row.names 过滤,您可以执行以下操作:

## Filter by rownames
row.names(dat) <- paste0("row_", row.names(dat))
dat

dn <- c("row_1","row_5","row_7")

dat[row.names(dat) %in% dn,]$result <- 3

dat

【讨论】:

  • 我需要根据行名进行匹配。谢谢你上面的解释,它让我很清楚。
  • 刚刚添加了按row.names过滤。
猜你喜欢
  • 2021-11-02
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 2019-08-05
  • 2022-07-07
相关资源
最近更新 更多