我一直试图将列中的多个值替换为它们的行名。在我的实际数据中,它们代表了一种主观测试,在这一点上,它要么被记录为阳性,要么记录为阴性。我必须在我的数据框架中对它进行重新分类,我所要做的就是示例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"有人能帮我处理这个吗。
发布于 2018-06-26 14:58:59
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这将不会由data.frame通过row.names过滤,而是按识别码过滤,但是由于它是一个有序的序列,所以您可以只使用这些索引进行转换。还是需要基于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
dathttps://stackoverflow.com/questions/51045130
复制相似问题