如果列的列有一个值,则如何用列中的CERO替换Na?使用r

发布于 2025-01-30 12:29:11 字数 285 浏览 5 评论 0原文

我想知道一种替换列的NA的方法,如果列的列有一个值意味着应该用CERO替换,如果列周围的列中没有值,则意味着他那天没有上班,而NA是正确的,

我一直在对其他列进行排序,但是因此,它很及时地消耗

我的样本称为DF的数据,真正的一列有30列,也有30,000行

  df <- data.frame(
  hours = c(NA, 3, NA, 8), 
  interactions = c(NA, 3, 9, 9),
  sales = c(1, 1, 1, NA)
)

I want to know a way to replace the NA of a column if the columns beside have a value, this because, using a example if the worker have values in the other columns mean he went to work that day so if he have an NA it means that should be replaced with cero, and if there are no values in the columns surrounding means he didnt go to work that day and the NA is correct

I have been doing this by sorting the other columns but its so time consuming

A sample of my data called df, the real one have 30 columns and like 30,000 rows

  df <- data.frame(
  hours = c(NA, 3, NA, 8), 
  interactions = c(NA, 3, 9, 9),
  sales = c(1, 1, 1, NA)
)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌路黄昏 2025-02-06 12:29:11
df$hours2 <- ifelse(
  test = is.na(df$hours) & any(!is.na(df[,c("interactions", "sales")])),
  yes = 0, 
  no = df$hours)

df
  hours interactions sales hours2
1    NA           NA     1      0
2     3            3     1      3
3    NA            9     1      0
4     8            9    NA      8
df$hours2 <- ifelse(
  test = is.na(df$hours) & any(!is.na(df[,c("interactions", "sales")])),
  yes = 0, 
  no = df$hours)

df
  hours interactions sales hours2
1    NA           NA     1      0
2     3            3     1      3
3    NA            9     1      0
4     8            9    NA      8
锦欢 2025-02-06 12:29:11

您也可以如下:

library(dplyr)

mutate(df, X = if_else(is.na(hours) | is.na(interactions), 0, hours))

#   hours interactions sales X
# 1    NA           NA     1 0
# 2     3            3     1 3
# 3    NA            9     1 0
# 4     8            9    NA 8

You could also do as follows:

library(dplyr)

mutate(df, X = if_else(is.na(hours) | is.na(interactions), 0, hours))

#   hours interactions sales X
# 1    NA           NA     1 0
# 2     3            3     1 3
# 3    NA            9     1 0
# 4     8            9    NA 8
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文