将数据框中的NA值使用for循环和if语句转换为任意整数

huangapple go评论56阅读模式
英文:

Converting NA values in a dataframe to an arbitrary integer with for loop and if statement

问题

我想将下面的数据框 d1 中的NA值转换为整数值,比如13,但似乎我的 for 循环和 if 语句不起作用。
如果有人能帮助我,我将不胜感激。

L3 <- LETTERS[1:3]
fac <- sample(L3, 10, replace = TRUE)
d <- data.frame(x = 1, y = 1:10, fac = fac)

d1 <- d
d1$x[1:3] <- NA
d1$y[4:6] <- NA
d1$fac[7:10] <- NA

for (i in 1:nrow(d1)){
  for (j in 1:ncol(d1)){
    if (is.na(d1[i,j]) == TRUE) {
      (d1[i,j]) == 13
    }
  }
}

请注意,您的代码中存在一个错误。要将NA值替换为整数值13,您应该使用 <- 而不是 ==。所以代码应该如下:

if (is.na(d1[i,j]) == TRUE) {
  d1[i,j] <- 13
}
英文:

I want to convert my NA values in below dataframe d1 to an integer value like 13 but it seems that my for loop and if statement wouldn't work.
I would appreciate if anyone could help me.

L3 &lt;- LETTERS[1:3]
fac &lt;- sample(L3, 10, replace = TRUE)
d &lt;- data.frame(x = 1, y = 1:10, fac = fac)

d1 &lt;- d
d1$x[1:3] &lt;- NA
d1$y[4:6] &lt;- NA
d1$fac[7:10] &lt;- NA

for (i in 1:nrow(d1)){
  for (j in 1:ncol(d1)){
    if (is.na(d1[i,j]) == TRUE) {
      (d1[i,j]) == 13
    }
  }
}

答案1

得分: 0

以下是您要翻译的内容:

"Result"

d1
#&gt;     x  y fac
#&gt; 1  13  1   A
#&gt; 2  13  2   B
#&gt; 3  13  3   C
#&gt; 4   1 13   B
#&gt; 5   1 13   A
#&gt; 6   1 13   B
#&gt; 7   1  7  13
#&gt; 8   1  8  13
#&gt; 9   1  9  13
#&gt; 10  1 10  13

<sup>创建于2023年02月24日,使用 reprex v2.0.2 </sup>

英文:

Probably due to typo.

L3 &lt;- LETTERS[1:3]
fac &lt;- sample(L3, 10, replace = TRUE)
d &lt;- data.frame(x = 1, y = 1:10, fac = fac)
d1 &lt;- d
d1$x[1:3] &lt;- NA
d1$y[4:6] &lt;- NA
d1$fac[7:10] &lt;- NA

for (i in 1:nrow(d1)){
  for (j in 1:ncol(d1)){
    if (is.na(d1[i,j])) {
      d1[i,j] &lt;-  13
    }
  }
}

Result

d1
#&gt;     x  y fac
#&gt; 1  13  1   A
#&gt; 2  13  2   B
#&gt; 3  13  3   C
#&gt; 4   1 13   B
#&gt; 5   1 13   A
#&gt; 6   1 13   B
#&gt; 7   1  7  13
#&gt; 8   1  8  13
#&gt; 9   1  9  13
#&gt; 10  1 10  13

<sup>Created on 2023-02-24 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年2月24日 15:15:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定