-1

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]]
[1] "MCA"

[[2]]
[1] "B.Com"

[[3]]
[1] "XII"

[[4]]
[1] "X"

I want to convert it like this :

> Degrees_df1
$Degrees1
[1] "MCA"

$Degrees2
[1] "B.Com"

$Degrees3
[1] "XII"

$Degrees4
[1] "X"

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

anindya
  • 61
  • 1
  • 12

1 Answers1

1

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.

Community
  • 1
  • 1
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • Hi @Zheyuan Li 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 – anindya Aug 20 '16 at 22:56
  • Sorry @Zheyuan Li I wanted to modify your code inside for loop using paste function. Please help me to solve this also.. – anindya Aug 20 '16 at 23:01
  • @ZheyuanLi ; I think your edit should have a stronger caveat that the op should rethink their workflow if they are trying to do it this way – user20650 Aug 20 '16 at 23:20
  • 4
    I would think that using `get` and `assign` within a `for` loop to add names to a list is almost certainly not the way to proceed. – user20650 Aug 20 '16 at 23:30