Maciej Dobrowolski
Maciej Dobrowolski

Reputation: 12122

R - Replacing element in list of vectors

I have list of vectors and want to assign vector to one position (override) of it. Here is sample code:

for (nodeId in names(chains)) {
    chains[nodeId] <- unlist(chains[nodeId])[-1]
}

After assignment I receive many warnings telling me that the lists are not of equal lengths. I understand that assignment which had taken place was not what I wanted.

Is there any way to just replace element in chains[nodeId] with object unlist(chains[nodeId])[-1]?

When I do str(chains), str(chains[nodeId]) and str(unlist(chains[nodeId])[-1]) I get following output:

$str(chains)
List of 15
 $ 4  : chr [1:3] "root" "alcohol< 9.85" "totalSulfurDioxide>=60.5"
 $ 10 : chr [1:4] "root" "alcohol< 9.85" "totalSulfurDioxide< 60.5" "sulphates< 0.575"
 $ 22 : chr [1:5] "root" "alcohol< 9.85" "totalSulfurDioxide< 60.5" "sulphates>=0.575" ...
 (...) lots more

$str(chains[nodeId])
List of 1
 $ 4: chr [1:3] "root" "alcohol< 9.85" "totalSulfurDioxide>=60.5"

$str(unlist(chains[nodeId])[-1])
Named chr [1:2] "alcohol< 9.85" "totalSulfurDioxide>=60.5"
 - attr(*, "names")= chr [1:2] "42" "43"

Update: str replaced with dput; added dput(chains[nodeId])

$ dput(chains)
structure(list(`4` = "alcohol< 9.85", `10` = "alcohol< 9.85", 
    `22` = "alcohol< 9.85", `92` = "alcohol< 9.85", `93` = "alcohol< 9.85", 
    `47` = "alcohol< 9.85", `24` = "alcohol>=9.85", `50` = "alcohol>=9.85", 
    `102` = "alcohol>=9.85", `103` = "alcohol>=9.85", `26` = "alcohol>=9.85", 
    `27` = "alcohol>=9.85", `28` = "alcohol>=9.85", `29` = "alcohol>=9.85", 
    `15` = c("root", "alcohol>=9.85", "alcohol>=11.55", "sulphates>=0.685"
    )), .Names = c("4", "10", "22", "92", "93", "47", "24", "50", 
"102", "103", "26", "27", "28", "29", "15"))

$ dput(chains[nodeId])
structure(list(`15` = c("root", "alcohol>=9.85", "alcohol>=11.55", 
"sulphates>=0.685")), .Names = "15")

$ dput(unlist(chains[nodeId])[-1))
structure(c("alcohol>=9.85", "alcohol>=11.55", "sulphates>=0.685"
), .Names = c("152", "153", "154"))

$ dput(chains[nodeId])
structure(list(`15` = "alcohol>=9.85"), .Names = "15")

What I want to achieve is to remove the first element from the vector in chains[nodeId]

Upvotes: 2

Views: 912

Answers (2)

Troy
Troy

Reputation: 8691

Is this what you want?

# make a list of vectors since no data provided
origlist<-lapply(1:3,function(x)c("a",paste0("b",x),"c"))
names(origlist)<-c("_1","_2","_3")

$`_1`
[1] "a"  "b1" "c" 

$`_2`
[1] "a"  "b2" "c" 

$`_3`
[1] "a"  "b3" "c" 

# remove first item from each as per your example
lapply(origlist, tail, n = -1)

$`_1`
[1] "b1" "c" 

$`_2`
[1] "b2" "c" 

$`_3`
[1] "b3" "c" 

Upvotes: 2

Richie Cotton
Richie Cotton

Reputation: 121077

If chains is a list and nodeId is a string, then chains[nodeId] will be a list of length one. You want chains[[nodeId]], which contains the contents of that list.

Upvotes: 3

Related Questions