【发布时间】:2019-11-21 20:41:51
【问题描述】:
我想替换列 rep1 到 rep4 中的数据。这些列中的数据与第一列中的唯一 ID 匹配。我想用对应 ID 行的值列中的数据替换列 rep1-rep4 中的数据。因此,对于第二行“b”,我想将“rep1”列中的“a”替换为“a”行中的相应值,在本例中为-400。
ID rep1 rep2 rep3 rep4 value
a -400
b a -300
c a b -200
d a b c -300
e a b c d -400
f -400
g f -400
h -400
i -200
j k l -300
k l -200
l -300
m -300
似乎使用ifelse(!is.na()) 可能可以在这里做点什么,但我不确定如何将列 rep1 到 rep4 中的 ID 数据与 ID 列中的相应行匹配,识别“值”中的哪些数据" 应该在替换中使用。这可以在同一个数据帧中完成,还是需要分成两个不同的数据帧才能工作?
这是使用dput()的数据
structure(list(ID = structure(1:13, .Label = c("a", "b", "c",
"d", "e", "f", "g", "h", "i", "j", "k", "l", "m"), class = "factor"),
rep1 = structure(c(1L, 2L, 2L, 2L, 2L, 1L, 3L, 1L, 1L, 4L,
5L, 1L, 1L), .Label = c("", "a", "f", "k", "l"), class = "factor"),
rep2 = structure(c(1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L,
1L, 1L, 1L), .Label = c("", "b", "l"), class = "factor"),
rep3 = structure(c(1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("", "c"), class = "factor"), rep4 = structure(c(1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("",
"d"), class = "factor"), value = c(-400L, -300L, -200L, -300L,
-400L, -400L, -400L, -400L, -200L, -300L, -200L, -300L, -300L
)), class = "data.frame", row.names = c(NA, -13L))
【问题讨论】:
-
您能以
dput格式发布您的示例数据吗?请使用dput(df)的输出编辑问题。或者,如果dput(head(df, 20))的输出太大。 (df是您的数据集的名称。) -
@RuiBarradas 我使用
dput将示例数据添加到问题的底部。
标签: r dataframe if-statement replace