警告:对于我这个初学者来说,这个问题似乎非常容易,但在 SO 上更复杂的主题中可能没有找到正确的解决方案(请参见 这里、这里、这里 和其他地方)。
我想要根据另一列,并使用其他列作为输入,在我的数据框中填充一列。
以下是一个更清晰的示例:
Version1 Version2 Version3 Version4 Presented_version Color
1 blue red green yellow 1 NA
2 red blue yellow green 4 NA
3 yellow green red blue 3 NA
我想用Version1/Version2/Version3/Version4中的一个值填充“Color”列。列Presented_version告诉我需要哪四个值之一。 例如,在第1行,Presented_version是1,所以所需的值在“Version1”(“blue”)中。第1行的颜色应该是蓝色。
有没有人能够向我展示一种不使用循环和大量“if”语句来完成此操作的方法?
structure(list(Version1 = structure(1:3, .Label = c("blue", "red",
"yellow"), class = "factor"), Version2 = structure(c(3L, 1L,
2L), .Label = c("blue", "green", "red"), class = "factor"), Version3 = structure(c(1L,
3L, 2L), .Label = c("green", "red", "yellow"), class = "factor"),
Version4 = structure(3:1, .Label = c("blue", "green", "yellow"
), class = "factor"), Presented_version = c(1L, 4L, 3L),
Color = c(NA, NA, NA)), class = "data.frame", row.names = c(NA,
-3L))
======================= 编辑完成!
我简化了例子以解释我的问题,但上面的例子与我的实际数据集在几个方面存在差异,因此解决方案做出了假设,而我的数据实际上并不符合这些假设。 以下是数据框的更准确表示。特别是,Presented_version与Version1...Version4列的内容之间没有固定的匹配(这取决于一个额外的列,我现在称之为Painter),而Version1到Version4不一定在我的数据集的第1到第4列中。
FillerColumn Painter Version1 Version2 Version3 Version4 Version_presented Color FillerColumn.1
1 77 A blue red green yellow 1 NA 77
2 77 B red blue yellow green 4 NA 77
3 77 C yellow green red blue 3 NA 77
4 77 D red blue yellow green 1 NA 77
structure(list(FillerColumn = c(77L, 77L, 77L, 77L), Painter = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Version1 = structure(c(1L,
2L, 3L, 2L), .Label = c("blue", "red", "yellow"), class = "factor"),
Version2 = structure(c(3L, 1L, 2L, 1L), .Label = c("blue",
"green", "red"), class = "factor"), Version3 = structure(c(1L,
3L, 2L, 3L), .Label = c("green", "red", "yellow"), class = "factor"),
Version4 = structure(c(3L, 2L, 1L, 2L), .Label = c("blue",
"green", "yellow"), class = "factor"), Version_presented = c(1L,
4L, 3L, 1L), Color = c(NA, NA, NA, NA), FillerColumn.1 = c(77L,
77L, 77L, 77L)), class = "data.frame", row.names = c(NA,
-4L))
df1[1:4]
中的[1:4]
是什么目的?没有它也可以运行。 - cropgen