我正在尝试在 R 中制定 2 个 for 循环。我需要分别用值“X”和“Y”填充 Iris 中的 2 列(ColA 和 ColB)。但我无法执行此操作。任何帮助将不胜感激
input <- c("X","Y")
col_names <- c("ColA", "ColB")
for (i in col_names){
for (j in input)
iris[[i]] <- paste0(j)
}
预期输出
Sepal.Length Sepal.Width Petal.Length Petal.Width Species ColA COlB
1 5.1 3.5 1.4 0.2 setosa X Y
2 4.9 3.0 1.4 0.2 setosa X Y
3 4.7 3.2 1.3 0.2 setosa X Y
4 4.6 3.1 1.5 0.2 setosa X Y
5 5.0 3.6 1.4 0.2 setosa X Y
6 5.4 3.9 1.7 0.4 setosa X Y
答案 0 :(得分:2)
这是您要找的吗?
myn <- 4
input <- sample(LETTERS, myn)
colnames <- paste0("Col", sample(LETTERS, myn))
if(length(input) == length(colnames)){
for(i in 1:length(input)){
iris$newcol <- input[i]
names(iris)[ncol(iris)] <- colnames[i]
}
} else{
cat("length(input) != length(colnames)")
}
head(iris)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species ColL ColM ColC ColY
# 1 5.1 3.5 1.4 0.2 setosa T J E I
# 2 4.9 3.0 1.4 0.2 setosa T J E I
# 3 4.7 3.2 1.3 0.2 setosa T J E I
# 4 4.6 3.1 1.5 0.2 setosa T J E I
# 5 5.0 3.6 1.4 0.2 setosa T J E I
# 6 5.4 3.9 1.7 0.4 setosa T J E I
答案 1 :(得分:0)
您可以使用:
input <- c("X","Y")
col_names <- c("ColA", "ColB")
df[col_names] <- as.list(input)
head(df)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species ColA ColB
#1 5.1 3.5 1.4 0.2 setosa X Y
#2 4.9 3.0 1.4 0.2 setosa X Y
#3 4.7 3.2 1.3 0.2 setosa X Y
#4 4.6 3.1 1.5 0.2 setosa X Y
#5 5.0 3.6 1.4 0.2 setosa X Y
#6 5.4 3.9 1.7 0.4 setosa X Y