user7906739
user7906739

Reputation:

How to name the element of the list in r?

Suppose I have this list:

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
}

Then I will get this:

  [[1]]
[1] 6

[[2]]
[1] 12

[[3]]
[1] 23

[[4]]
[1] 14

How to name the element of the output, like this:

 > my_variable
    First_result
[1] 6

    Second_result
[1] 12

and so on.

Upvotes: 1

Views: 87

Answers (1)

Miha
Miha

Reputation: 2874

You could do it with the paste0 and names

# 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

Upvotes: 1

Related Questions