colnames中的变量

时间:2016-07-28 08:41:12

标签: r

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

list_names <- "Henk", "Ash", "Brock", "Piet"
list_age <- 14 , 12, 44, 56

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

我尝试了这个,但是得到了Colnames有很多争论的错误。

有人知道如何将这些变量放在像Colnames这样的变量中吗?

KR, Arnand

3 个答案:

答案 0 :(得分:1)

我们可能需要paste(使用R

colnames(df) <- paste("This is my name", list_names, "and I'am", list_age)
colnames(df)
#[1] "This is my name Henk and I'am 14"  "This is my name Ash and I'am 12"   "This is my name Brock and I'am 44"
#[4] "This is my name Piet and I'am 56" 

数据

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)

答案 1 :(得分:0)

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." 

答案 2 :(得分:0)

使用paste

不要使用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.")