如何用特定字符串字符替换列中的特定 NA
这可能很简单,但我无法弄清楚
df<-structure(list(Besti = c("Friend", "myfriend", "yourbest", "allbest"
), Friend = c("Friend", NA, "Friend", "Toofriend"), Val1 = c(0L,
0L, 0L, 0L), Val2 = c(0L, 0L, 0L, 0L), Val3 = c(0L, 1L, 0L, 0L
), Val4 = c(0L, 0L, 0L, 0L), Val5 = c(0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-4L))
我的数据是这样的,我想知道如果一个较高的字符串和一个较低的字符串相同,如何将 NA 替换为字符串
所以我可以发现有一个 NA
sum(is.na(df$Friend))
如果它是一个较高的朋友,一个较低的朋友,我想将其替换为朋友,
所以输出看起来像这样
df_out<-structure(list(Besti = c("Friend", "myfriend", "yourbest", "allbest"
), Friend = c("Friend", "Friend", "Friend", "Toofriend"), Val1 = c(0L,
0L, 0L, 0L), Val2 = c(0L, 0L, 0L, 0L), Val3 = c(0L, 1L, 0L, 0L
), Val4 = c(0L, 0L, 0L, 0L), Val5 = c(0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-4L))
,想象我有 100 个或多个 HA,并且没有顺序,也许前面的一个是 NA,或者后面的一个是 NA,但是这两个之后是 Friend 或任何字符串
如果我想要将 NA 替换为 Friend,我可以这样做
df$Friend <- df$Friend %>% replace_na('Friend')
This could be very simple to but I could not figure
df<-structure(list(Besti = c("Friend", "myfriend", "yourbest", "allbest"
), Friend = c("Friend", NA, "Friend", "Toofriend"), Val1 = c(0L,
0L, 0L, 0L), Val2 = c(0L, 0L, 0L, 0L), Val3 = c(0L, 1L, 0L, 0L
), Val4 = c(0L, 0L, 0L, 0L), Val5 = c(0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-4L))
My data is like this, I want to know how to replace the NA to a string if one higher and one lower string is the same
So I can find that there is an NA
sum(is.na(df$Friend))
If it is one higher friend and one lower is friend, I want to replace it to friend
so the output look like this
df_out<-structure(list(Besti = c("Friend", "myfriend", "yourbest", "allbest"
), Friend = c("Friend", "Friend", "Friend", "Toofriend"), Val1 = c(0L,
0L, 0L, 0L), Val2 = c(0L, 0L, 0L, 0L), Val3 = c(0L, 1L, 0L, 0L
), Val4 = c(0L, 0L, 0L, 0L), Val5 = c(0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-4L))
so imagine I have 100 HAs or many and there is no order, maybe one before is NA or one after is NA but the two after is Friend or whatever string
If I want to replace the NA to Friend, I can do this
df$Friend <- df$Friend %>% replace_na('Friend')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
dplyr::lag()
和dplyr::lead()
向下/向上移动矢量Friend
。然后我们可以测试它们是否具有相同的值,如果是,我们就使用它
值作为重置值。
dplyr::coalesce()
替换 NAFriend
与replacement
值处于同一位置。这可以简化为:
dplyr::lag()
anddplyr::lead()
shift the vectorFriend
down/up.We can then test if they have the same value and if they do we use this
value as the replacement value.
dplyr::coalesce()
replaces the NAs inFriend
with thereplacement
value in the same postion.This can be simplified to:
这是另一种方法。在数据框中,我添加了每次观察之前和之后出现的
Friend
值:输出:
现在我们可以导出
Friend
的新版本> 带有ifelse()
的变量:输出:
Here's another approach. To the data frame I added the values of
Friend
that come before and after each observation:Output:
Now we can derive a new version of the
Friend
variable withifelse()
:Output: