gpt4 book ai didi

r - 覆盖使用 Dplyr - R 过滤的 data.frame 上的值

转载 作者:行者123 更新时间:2023-12-05 04:59:44 26 4
gpt4 key购买 nike

我有一个名为 cleandata 的数据框,需要更改 age 列的值。

我可以从 dplyr 中找到要用 filterselect 函数替换的值。

> str(cleantrain)
'data.frame': 891 obs. of 9 variables:
$ train$PassengerId: int 1 2 3 4 5 6 7 8 9 10 ...
$ survived : Factor w/ 2 levels "0","1": 1 2 2 2 1 1 1 1 2 2 ...
$ Title : Factor w/ 17 levels "Capt","Col","Don",..: 12 13 9 13 12 12 12 8 13 13 ...
$ fare : num 7.25 71.28 7.92 53.1 8.05 ...
$ sbsp : int 1 1 0 1 0 0 0 3 0 1 ...
$ parch : int 0 0 0 0 0 0 0 1 2 0 ...
$ alone : Factor w/ 2 levels "0","1": 1 1 2 1 2 2 2 1 1 1 ...
$ familysize : Factor w/ 9 levels "1","2","3","4",..: 2 2 1 2 1 1 1 5 3 2 ...
$ age : num 22 38 26 35 35 NA 54 2 27 14 ...

# Column title is equal to "Master" and Column age is NA
> cleantrain %>% filter(Title == "Master" & is.na(age))
train$PassengerId survived Title fare sbsp parch alone familysize age
1 66 1 Master 15.2458 1 1 0 3 NA
2 160 0 Master 69.5500 8 2 0 11 NA
3 177 0 Master 25.4667 3 1 0 5 NA
4 710 1 Master 15.2458 1 1 0 3 NA

我只需要将这些 NA 替换为 8。如下使用 mutate 不会更新原始的 cleantrain data.frame

>cleantrain %>% filter(Title == "Master" & is.na(age)) %>% mutate(age = 8) #will put the right info on the right place.

train$PassengerId survived Title fare sbsp parch alone familysize age
1 66 1 Master 15.2458 1 1 0 3 8
2 160 0 Master 69.5500 8 2 0 11 8
3 177 0 Master 25.4667 3 1 0 5 8
4 710 1 Master 15.2458 1 1 0 3 8

#but not actually. when checking dataframe values remains NAS

>cleantrain %>% filter(Title == "Master" & is.na(age))

train$PassengerId survived Title fare sbsp parch alone familysize age
1 66 1 Master 15.2458 1 1 0 3 NA
2 160 0 Master 69.5500 8 2 0 11 NA
3 177 0 Master 25.4667 3 1 0 5 NA
4 710 1 Master 15.2458 1 1 0 3 NA

我可以使用 mutate 来做到这一点吗?任何不需要 for/if 循环的 Dplyr/quick 函数?#learningR

最佳答案

如果您想用固定值更新行,@akrun 的replace 解决方案将起作用。通常,您必须使用 ifelse 函数,我相信:

cleantrain <- cleantrain %>% 
mutate(age = ifelse(Title == 'Master' & is.na(age),
8,
age))

关于r - 覆盖使用 Dplyr - R 过滤的 data.frame 上的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63366834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com