R colnames中的变量

R colnames中的变量,r,R,我想在Colnames中组合文本和变量。 我尝试过的示例(Python和R的混合): list\u name我们可能需要粘贴(使用R) colnames(df)for循环中的修改 for (i in 1:4){ names(df)[i] <- paste(c("This is my name ",list_names[i]," and I'am ",list_age[i]," years old."),collapse="") } names(df) [1] "This is my na

我想在Colnames中组合文本和变量。 我尝试过的示例(Python和R的混合):


list\u name我们可能需要
粘贴
(使用
R


colnames(df)for循环中的修改

for (i in 1:4){
names(df)[i] <- paste(c("This is my name ",list_names[i]," and I'am ",list_age[i]," years old."),collapse="")
}

names(df)
[1] "This is my name Henk and I'am 14 years old."  "This is my name Ash and I'am 12 years old."  
[3] "This is my name Brock and I'am 44 years old." "This is my name Piet and I'am 56 years old." 
for(1:4中的i){

名称(df)[i]使用
粘贴

不要使用
range
,因为在R中它的意思与在Python中完全不同

除非必要,否则不要使用列表。尽可能使用向量

paste
将乐于接受向量,甚至向量和标量的混合

df <- matrix(,10,4)
names <- c("Henk", "Ash", "Brock", "Piet") 
ages <- c(14, 12, 44, 56)
colnames(df) <- paste("This is my name", names, "and I'am", ages, "years old.")

df您是否需要
粘贴
粘贴(“这是我的名字”,列出姓名,“我是”,列出年龄)
这是一个不同的解决方案。我在发布前7分钟发布了相同的解决方案
list_names <- c("Henk", "Ash", "Brock", "Piet")
list_age <- c(14 , 12, 44, 56)
df <- data.frame(v1 = 1:4, v2 = 2:5, v3 = 3:6, v4 = 4:7)
for (i in 1:4){
names(df)[i] <- paste(c("This is my name ",list_names[i]," and I'am ",list_age[i]," years old."),collapse="")
}

names(df)
[1] "This is my name Henk and I'am 14 years old."  "This is my name Ash and I'am 12 years old."  
[3] "This is my name Brock and I'am 44 years old." "This is my name Piet and I'am 56 years old." 
df <- matrix(,10,4)
names <- c("Henk", "Ash", "Brock", "Piet") 
ages <- c(14, 12, 44, 56)
colnames(df) <- paste("This is my name", names, "and I'am", ages, "years old.")