如何在数据框架的一列中替换Na值,并用不同的数据框中的列中的值替换值?

发布于 2025-02-11 01:45:16 字数 239 浏览 3 评论 0原文

如何将“示例”中的NA值替换为“示例2”中的相应值?因此,7将代替第一个NA,而8将代替第二个NA等。我的数据大得多,因此我将无法单独重命名多个NAS的值。谢谢

example <- data.frame('count' = c(1,3,4,NA,8,NA,9,0,NA,NA,7,5,8,NA))
    
example2 <- data.frame('count' = c(7,8,4,6,7))

How do I replace the NA values in 'example' with the corresponding values in 'example 2'? So 7 would take the place of the first NA and 8 would take the place of the second NA etc. My data is much larger so I would not be able to rename the values individually for the multiple NAs. Thanks

example <- data.frame('count' = c(1,3,4,NA,8,NA,9,0,NA,NA,7,5,8,NA))
    
example2 <- data.frame('count' = c(7,8,4,6,7))

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

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

发布评论

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

评论(3

煮酒 2025-02-18 01:45:16

基于替换的另一个可能的解决方案:

example$count <- replace(example$count, is.na(example$count), example2$count)
example

#>    count
#> 1      1
#> 2      3
#> 3      4
#> 4      7
#> 5      8
#> 6      8
#> 7      9
#> 8      0
#> 9      4
#> 10     6
#> 11     7
#> 12     5
#> 13     8
#> 14     7

Another possible solution, based on replace:

example$count <- replace(example$count, is.na(example$count), example2$count)
example

#>    count
#> 1      1
#> 2      3
#> 3      4
#> 4      7
#> 5      8
#> 6      8
#> 7      9
#> 8      0
#> 9      4
#> 10     6
#> 11     7
#> 12     5
#> 13     8
#> 14     7
凉风有信 2025-02-18 01:45:16

您可以尝试:

example[is.na(example),] <- example2 

这将为您提供:

count
1      1
2      3
3      4
4      7
5      8
6      8
7      9
8      0
9      4
10     6
11     7
12     5
13     8
14     7

编辑:,由于您的数据范围内的一列可能不止一列,因此您应该使用:

example$count[is.na(example$count)] <- example2$count

You can try with :

example[is.na(example),] <- example2 

Which will give you :

count
1      1
2      3
3      4
4      7
5      8
6      8
7      9
8      0
9      4
10     6
11     7
12     5
13     8
14     7

EDIT: Since you probably have more than just one column in your dataframes, you should use :

example$count[is.na(example$count)] <- example2$count
伪装你 2025-02-18 01:45:16

使用的另一个选项要检查Na值的索引:

ind <- which(is.na(example$count))
example[ind, "count"] <- example2$count

输出:

   count
1      1
2      3
3      4
4      7
5      8
6      8
7      9
8      0
9      4
10     6
11     7
12     5
13     8
14     7

Another option using which to check the index of NA values:

ind <- which(is.na(example$count))
example[ind, "count"] <- example2$count

Output:

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