如何为列表的每个对象添加名称

时间:2016-06-19 14:19:30

标签: r

我有一个如下所示的列表

#H2 Server Properties
0=H2 File|org.h2.Driver|jdbc\:h2\:file\:~/test;DB_CLOSE_ON_EXIT=FALSE

# Enable if you want other applications to connect
#webAllowOthers=true
#webPort=8082
#webSSL=false

我想要的是为这个列表的每个对象添加名称 例如

d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
my.list <- list(d1, d2)
str(my.list)
List of 2
 $ :'data.frame':   3 obs. of  2 variables:
  ..$ y1: num [1:3] 1 2 3
  ..$ y2: num [1:3] 4 5 6
 $ :'data.frame':   3 obs. of  2 variables:
  ..$ y1: num [1:3] 3 2 1
  ..$ y2: num [1:3] 6 5 4

我厌倦了

 $myFirst :'data.frame':    3 obs. of  2 variables:
  ..$ y1: num [1:3] 1 2 3
  ..$ y2: num [1:3] 4 5 6
 $mySecond :'data.frame':   3 obs. of  2 variables:
  ..$ y1: num [1:3] 3 2 1
  ..$ y2: num [1:3] 6 5 4

问题出在哪里?

该功能不起作用的新数据

myNam<-c("myFirst","mySecond")
names(myNam) <- sapply(my.list,paste)

1 个答案:

答案 0 :(得分:2)

我们需要将“myNam”分配给names的{​​{1}}

my.list

names(my.list) <- myNam str(my.list) #List of 2 #$ myFirst :'data.frame': 3 obs. of 2 variables: # ..$ y1: num [1:3] 1 2 3 # ..$ y2: num [1:3] 4 5 6 #$ mySecond:'data.frame': 3 obs. of 2 variables: # ..$ y1: num [1:3] 3 2 1 # ..$ y2: num [1:3] 6 5 4

setNames

OP的代码

setNames(my.list, myNam)

循环遍历sapply(my.list,paste) 个元素,list将列的元素循环到单个字符串。