Jusep
Jusep

Reputation: 187

R: How to select the first element of one vector inside a list

I would like to replace the first element of my list (a vector) for the first value of that vector. So if we have:

x <- (2, 4, 6)
list <- list(r1 = x, r2 = pi, r3 = month.name)

How could I replace the element r1 in my list, with the first element of r1 (2)? I would like an outcome like this:

list
$r1
[1] 2
$r2
[1] 3.141593
$r3
[1] "January"   "February"  "March"     "April"     "May"       "June"     
[7] "July"      "August"    "September" "October"   "November"  "December" 

Upvotes: 0

Views: 4146

Answers (1)

akrun
akrun

Reputation: 887018

Extract the list element and assign back after subsetting

list$r1 <- list$r1[1]

-output

list
#$r1
#[1] 2

#$r2
#[1] 3.141593

#$r3
#[1] "January"   "February"  "March"     "April"     "May"       "June"      "July"      "August"    "September" "October"   "November" 
#[12] "December" 

Upvotes: 1

Related Questions