R ifelse 替换列中的值 [英] R ifelse to replace values in a column

查看:32
本文介绍了R ifelse 替换列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框中有一列如下:

I have a column in my dataframe as follows:

Private
Private
Private
 ?
Private

我想替换这个?"与私人.我有一个解决方案如下:

I want to replace this " ?" with Private. I have a solution as follows:

# Only replacing ? with Private 
df$var <- ifelse(df$var == " ?", " Private", df$var)

但是,当我在 ifelse 语句之后打印出 df$var 列时,这些值似乎不正确.这是我得到的:

However when I print out the df$var column after the ifelse statement, these values don't seem correct. This is what I got:

3
3
3
Private
3

我不知道这里出了什么问题.

I don't know what went wrong here.

推荐答案

这应该有效,使用工作示例:

This should work, using the working example:

var <- c("Private", "Private", "?", "Private")
df <- data.frame(var)
df$var[which(df$var == "?")] = "Private"

然后这将替换?"的值带有私人"

Then this will replace the values of "?" with "Private"

您的替换不起作用的原因(我认为)是好像 df$var 中的值不是 "?" 然后它替换了整个 df$var 列的向量,而不仅仅是重新插入您想要的元素.

The reason your replacement isn't working (I think) is as if the value in df$var isn't "?" then it replaces the element of the vector with the whole df$var column, not just reinserting the element you want.

这篇关于R ifelse 替换列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆