如何在r中命名列表元素?

时间:2017-07-03 18:44:05

标签: r

假设我有这个清单:

my_variable <- list()
x <- c(1,2,3,4)
y <- c(4,5,7,3)
for ( i in 1:4){
my_variable[[i]] <- x[i]*y[i]+2
}

然后我会得到这个:

  [[1]]
[1] 6

[[2]]
[1] 12

[[3]]
[1] 23

[[4]]
[1] 14

如何命名输出元素,如下所示:

 > my_variable
    First_result
[1] 6

    Second_result
[1] 12

等等。

1 个答案:

答案 0 :(得分:1)

您可以使用paste0names

执行此操作
# So first you define vector of names:
names1 <- c("First","Second","Third","Fourth")
# And second you paste them to your list
names(my_variable) <- paste0(names1,"_result",  sep = "")

#And the output
$First_result
[1]  6 12 23 14

$Second_result
[1]  6 12 23 14

$Third_result
[1]  6 12 23 14

$Fourth_result
[1]  6 12 23 14