用字符替换空白单元格

问题描述 投票:0回答:5

我正在研究如下所示的数据集:

191  
282 A

202  
210 B

我想用一个字符替换第二列中的空单元格,例如“N”。我怎样才能在 R 中有效地做到这一点?

欣赏它。

r
5个回答
23
投票

数据框示例:

dat <- read.table(text = "
191 ''
282 A
202 ''
210 B")

您可以使用

sub
将空字符串替换为
"N"
:

dat$V2 <- sub("^$", "N", dat$V2)

#    V1 V2
# 1 191  N
# 2 282  A
# 3 202  N
# 4 210  B

11
投票

另一种方式:

假设与 wibeasley 相同的数据结构:

ds <- data.frame(ID=c(191, 282, 202, 210), Group=c("", "A", "", "B"), stringsAsFactors=FALSE)

你可以写:

ds$Group[ds$Group==""]<-"N"

4
投票

如果你的 data.frame 是这样的。

ds <- data.frame(ID=c(191, 282, 202, 210), Group=c("", "A", "", "B"), stringsAsFactors=FALSE)

可以检查每个元素的长度,如果长度为零则用“N”替换。

ds$Group <- ifelse(nchar(ds$Group)==0, "N", ds$Group)

0
投票

还有两条记录的日期格式不符合时间。我也必须删除那些。

# df1 column "date" has this format: 2016-04-28 22:30:00
# remove rows that do not match this format
ck1 <- ck1 %>% 
  filter(grepl("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}", ckdate))

-1
投票
DataFrame$FeatureName[which(DataFrame$FeatureName == "")] <- "N"
© www.soinside.com 2019 - 2024. All rights reserved.