Reputation: 2341
My data is as follows:
library(data.table)
df <- fread(
"A B C D E F iso year
0 A NA 1 NA NA NLD 2009
1 Y NA 2 NA NA NLD 2009
0 Q NA 3 NA NA AUS 2011
1 NA NA 4 NA NA AUS 2011
0 0 NA 7 NA NA NLD 2008
1 1 NA 1 NA NA NLD 2008
0 1 NA 3 NA NA AUS 2012
0 NA 1 NA 1 NA ECU 2009
1 NA 0 NA 2 0 ECU 2009
0 NA 0 NA 3 0 BRA 2011
1 NA 0 NA 4 0 BRA 2011
0 NA 1 NA 7 NA ECU 2008
1 NA 0 NA 1 0 ECU 2008
0 NA 0 NA 3 2 BRA 2012
1 NA 0 NA 4 NA BRA 2012",
header = TRUE
)
# Creates a list of dataframes
df_iso <- split(df, df$iso) # Creates a list of dataframes
I would now like to extract the column name of column 8 in each dataset of the list.
Obviously in this case they are all "year"
, but in my actual data they are different.
If I do colnames(df_iso[[1]])[8]
I get "year"
, so I tried:
I tried:
names <- list()
for (i in length(df_iso)) {
names <- as.vector(append(names , colnames(df_iso[[i]])[8]))
}
Surprisingly that does not work. I would like either a list or a vector which for each data.frame in df_iso
gives me `"year"``, can anyone help?
Upvotes: 1
Views: 41
Reputation: 3060
Solution using sapply:
sapply(df_iso, function(i){
colnames(i)[8]
})
AUS BRA ECU NLD
"year" "year" "year" "year"
Upvotes: 0
Reputation: 39858
One possibility could be:
lapply(df_iso, function(x) names(x)[8])
$AUS
[1] "year"
$BRA
[1] "year"
$ECU
[1] "year"
$NLD
[1] "year"
Upvotes: 2