Вопрос

I have the following example named list:

> named_list <- c(0,0,0)
> names(named_list) <- c('a','b','c')
> named_list
a b c 
0 0 0 

And I have a vector with values that I want to have changed

> set_to_1 <- c('b','c','d')

So now I change the values

> named_list[set_to_1] <- 1

And I get

> named_list
a b c d 
0 1 1 1 

However, I would like to get

> named_list
a b c
0 1 1

How can I do this?

Это было полезно?

Решение

Maybe this should work for you:

named_list[names(named_list) %in% set_to_1] <- 1
named_list
# a b c 
# 0 1 1 

Or this:

named_list[intersect(names(named_list), set_to_1)] <- 1
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top