r - 我想用以前的非 NA 值和“Unclassified_”替换表中的 NA
问题描述
使用 R:我需要用最接近左侧的值以及“未分类_”填充任何 NA 单元格
下面的代码完美地填充了左边最接近的值,但我不知道如何在之前放置永久字符串“Unclassified_”
library(zoo)
y <- t(na.locf(t(x), fromLast=F)) #Fill NA cells with closest value to the left
示例数据
set.seed(1)
x <- data.frame(a=sample(c(1,2), 10, replace=T),
b=sample(c(1,2,NA), 10, replace=T),
c=sample(c(1:5,NA), 10, replace=T))
给出df:
a b c
2 NA 1
2 2 1
1 NA 5
1 1 2
1 1 NA
1 NA 4
1 1 5
2 2 NA
2 2 NA
1 NA 2
而且我要:
a b c
2 unclassifed_2 1
2 2 1
1 unclassifed_1 5
1 1 2
1 1 unclassified_1
1 unclassified_1 4
1 1 5
2 2 unclassified_2
2 2 unclassified_2
1 unclassified_1 2
解决方案
x$b[is.na(x$b)] = paste0("unclassifed_", x$a)
x$c[is.na(x$c)] = paste0("unclassifed_", x$a)
推荐阅读
- jointjs - addTools 在 rappidjs 中给出异常
- spring-boot - Spring Boot + Apache Wicket - JSP 页面正在下载而不是渲染
- java - 如何在 Resttemplate Spring 中做
- javascript - 如何构建一个无限的画布并有能力将图纸保存和恢复到原来的位置?
- android - 两个具有相同 ID 但不同通知渠道的通知
- node.js - 如何使用momentjs在mysql中保存本地时区的日期时间
- three.js - 修改后的网格照明看起来不正确
- android - 如何处理启动阶段Android应用程序的崩溃?
- c# - 3D Secure 2.0 与 Braintree 订阅的集成
- tensorflow - Tensorflow 中的 sparse_image_warp 不起作用?