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

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

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

问题

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

  1. L3 <- LETTERS[1:3]
  2. fac <- sample(L3, 10, replace = TRUE)
  3. d <- data.frame(x = 1, y = 1:10, fac = fac)
  4. d1 <- d
  5. d1$x[1:3] <- NA
  6. d1$y[4:6] <- NA
  7. d1$fac[7:10] <- NA
  8. for (i in 1:nrow(d1)){
  9. for (j in 1:ncol(d1)){
  10. if (is.na(d1[i,j]) == TRUE) {
  11. (d1[i,j]) == 13
  12. }
  13. }
  14. }

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

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

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.

  1. L3 &lt;- LETTERS[1:3]
  2. fac &lt;- sample(L3, 10, replace = TRUE)
  3. d &lt;- data.frame(x = 1, y = 1:10, fac = fac)
  4. d1 &lt;- d
  5. d1$x[1:3] &lt;- NA
  6. d1$y[4:6] &lt;- NA
  7. d1$fac[7:10] &lt;- NA
  8. for (i in 1:nrow(d1)){
  9. for (j in 1:ncol(d1)){
  10. if (is.na(d1[i,j]) == TRUE) {
  11. (d1[i,j]) == 13
  12. }
  13. }
  14. }

答案1

得分: 0

以下是您要翻译的内容:

"Result"

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

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

英文:

Probably due to typo.

  1. L3 &lt;- LETTERS[1:3]
  2. fac &lt;- sample(L3, 10, replace = TRUE)
  3. d &lt;- data.frame(x = 1, y = 1:10, fac = fac)
  4. d1 &lt;- d
  5. d1$x[1:3] &lt;- NA
  6. d1$y[4:6] &lt;- NA
  7. d1$fac[7:10] &lt;- NA
  8. for (i in 1:nrow(d1)){
  9. for (j in 1:ncol(d1)){
  10. if (is.na(d1[i,j])) {
  11. d1[i,j] &lt;- 13
  12. }
  13. }
  14. }

Result

  1. d1
  2. #&gt; x y fac
  3. #&gt; 1 13 1 A
  4. #&gt; 2 13 2 B
  5. #&gt; 3 13 3 C
  6. #&gt; 4 1 13 B
  7. #&gt; 5 1 13 A
  8. #&gt; 6 1 13 B
  9. #&gt; 7 1 7 13
  10. #&gt; 8 1 8 13
  11. #&gt; 9 1 9 13
  12. #&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:

确定