[英]R updating dataframe elements given that a separate column element exists in another vector
I have a vector vec:我有一个向量 vec:
a<-c(4,2,9,2)
And a dataframe df:和一个数据框df:
indx explore_ind
1 1 dark
2 2 dark
3 3 dark
4 4 dark
5 5 dark
6 6 dark
7 7 dark
8 8 dark
9 9 dark
10 10 dark
df<-structure(list(indx = 1:10, explore_ind = c("dark", "dark", "dark",
"dark", "dark", "dark", "dark", "dark", "dark", "dark")), row.names = c(NA,
10L), class = "data.frame")
I would like to update any explore_ind from "dark" to "light" where indx exists in vec.我想将任何 explore_ind 从“dark”更新为“light”,其中 indx 存在于 vec 中。
The result should be:结果应该是:
indx explore_ind
1 1 dark
2 2 light
3 3 dark
4 4 light
5 5 dark
6 6 dark
7 7 dark
8 8 dark
9 9 light
10 10 dark
In base R在基础 R
The square brackets allows us to subset by index when we are subseting a vector, which is what we have when we use $
on a column name方括号允许我们在对向量进行子集化时按索引进行子集化,这就是我们在列名上使用$
时所拥有的
df$explore_ind[a] <- "light"
If indx isn't sorted you can use如果 indx 未排序,您可以使用
df$explore_ind[df$indx %in% a] <- "light"
as suggested by @user2974951正如@user2974951 所建议的那样
ifelse
option: ifelse
选项:
df$explore_ind <- ifelse(df$indx %in% a, "light", "dark")
df
Output:输出:
indx explore_ind
1 1 dark
2 2 light
3 3 dark
4 4 light
5 5 dark
6 6 dark
7 7 dark
8 8 dark
9 9 light
10 10 dark
library(tidyverse)
df<-structure(list(indx = 1:10, explore_ind = c("dark", "dark", "dark",
"dark", "dark", "dark", "dark", "dark", "dark", "dark")), row.names = c(NA,
10L), class = "data.frame") %>%
as_tibble()
a<-c(4,2,9,2)
df %>%
mutate(explore_ind = case_when(indx %in% a ~ "light",
TRUE ~ explore_ind))
#> # A tibble: 10 x 2
#> indx explore_ind
#> <int> <chr>
#> 1 1 dark
#> 2 2 light
#> 3 3 dark
#> 4 4 light
#> 5 5 dark
#> 6 6 dark
#> 7 7 dark
#> 8 8 dark
#> 9 9 light
#> 10 10 dark
Created on 2022-06-29 by the reprex package (v2.0.1)由reprex 包于 2022-06-29 创建 (v2.0.1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.