anindya anindya - 1 year ago 59
R Question

Convert list to named list in R

I am very new in R language.I want to change name of list element number.

Currently I have list like this :(screen shot from R Studio)

> Degrees_df1
[1] "MCA"

[1] "B.Com"

[1] "XII"

[1] "X"

I want to convert it like this :

> Degrees_df1
[1] "MCA"

[1] "B.Com"

[1] "XII"

[1] "X"

I am new in R language any kind of help will be grateful for me.Thanks in advance.......

Answer Source

So you want your list to have names:

NAME <- paste0("Degrees", 1:length(Degrees_df1))

Any of the following is OK:

names(Degrees_df1) <- NAME

attr(Degrees_df1, "names") <- NAME

Degrees_df1 <- "names<-"(Degrees_df1, NAME)

Degrees_df1 <- setNames(Degrees_df1, NAME)

Degrees_df1 <- structure(Degrees_df1, names = NAME)

But I think, the best thing is to give names when you create the list. For example, if you do:

list(1, 2, 3, 4)

the resulting list has no names. While if you do

list(a = 1, b= 2, c = 3, d = 4)

the resulting list has names.

If I am applying paste function over there I am getting error like this:

Error in assign(names(paste0("Degrees_df", i)), paste0("Degrees", 1:length(get(paste0("Degrees_df", : invalid first argument

Sorry, I wanted to modify your code inside for loop using paste function.

You possibly need this (not efficient):

df_i <- get(paste0("Degrees_df", i))   ## a local variable
names(df_i) <- paste0("Degrees", 1:length(df_i))    ## modify local variable
assign(paste0("Degrees_df", i), df_i)   ## write back and update

or (better):

df_i <- get(paste0("Degrees_df", i))   ## a local variable
assign(paste0("Degrees_df", i),
       setNames(df_i, paste0("Degrees", 1:length(df_i))))
# assign(paste0("Degrees_df", i),
#        "names<-"(df_i, paste0("Degrees", 1:length(df_i))))
# assign(paste0("Degrees_df", i),
#        structure(df_i, names = paste0("Degrees", 1:length(df_i))))

assign is used to assign value (or another variable) to a variable. It looks like your error code tries to assign names attributes. Note, the names of a list / data.frame is "attributes", not a variable, so you can not use assign to change them.