英文:
How to replace the dataset with one value if it satisfies a condition, if not with another value
问题
我有一个包含30列的数据集。一个示例看起来可能像这样:
data <- data.frame(name=c("A", "B", "C", "D", "E", "C", "A", "B"),
place=c("B", "c", "F", "C", "G", "A", "H", "A"))
现在我想将整个数据集的值替换为1,如果name等于A,并且不等于1则替换为0。
英文:
I have a dataset with 30 columns. An example would look something like this
data <- data.frame(name=c("A", "B", "C", "D", "E", "C", "A", "B"),
place=c("B", "c", "F", "C", "G", "A", "H", "A"))
Now I would like to replace the whole of dataset with value of 1 if name=A and with 0 if not equal to 1.
答案1
得分: 1
如果您想要替换数据集中 name == 'A'
的行,您可以执行以下操作:
library(dplyr)
data <- data.frame(name=c("A", "B", "C", "D", "E", "C", "A", "B"),
place=c("B", "c", "F", "C", "G", "A", "H", "A"))
data %>%
mutate(
across(.fns = ~ if_else(name == "A", 1, 0))
)
或者,如果您想要将数据中所有 'A'
的值替换为1,其他值替换为0,可以执行以下操作:
library(dplyr)
data <- data.frame(
name = c("A", "B", "C", "D", "E", "C", "A", "B"),
place = c("B", "c", "F", "C", "G", "A", "H", "A")
)
data %>%
mutate(
across(.fns = ~ if_else(.x == "A", 1, 0))
)
希望这有帮助。
英文:
If you want to replace the row of the dataset where name == 'A'
, you can do the follwoing,
library(dplyr)
data <- data.frame(name=c("A", "B", "C", "D", "E", "C", "A", "B"),
place=c("B", "c", "F", "C", "G", "A", "H", "A"))
data %>%
mutate(
across(.fns = ~ if_else(name == "A", 1, 0))
)
#> name place
#> 1 1 1
#> 2 0 0
#> 3 0 0
#> 4 0 0
#> 5 0 0
#> 6 0 0
#> 7 1 1
#> 8 0 0
<sup>Created on 2023-01-06 by the reprex package (v2.0.1)</sup>
Or, if you want to replace all value of the data for 'A'
with 1 or else 0 for other value,
library(dplyr)
data <- data.frame(
name = c("A", "B", "C", "D", "E", "C", "A", "B"),
place = c("B", "c", "F", "C", "G", "A", "H", "A")
)
data %>%
mutate(
across(.fns = ~ if_else(.x == "A", 1, 0))
)
#> name place
#> 1 1 0
#> 2 0 0
#> 3 0 0
#> 4 0 0
#> 5 0 0
#> 6 0 1
#> 7 1 0
#> 8 0 1
<sup>Created on 2023-01-06 by the reprex package (v2.0.1)</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论