数据集调用:有一个数据帧df,如下所示:
# df
No. Sub_No. Req_No.
130 1 231
130 2 ""
130 3 ""
121 1 ""
140 1 398
140 2 ""
期望的输出
# df
Type No. Sub_No. Req_No.
A 130 1 231
A 130 2 ""
A 130 3 ""
121 1 ""
A 140 1 398
A 140 2 ""
我只有接近:
df["Type"] <- ifelse(grepl("[[:digit:]]",df$Req_No.),"A","-")
显然它可以实现所需的数据集。
答案 0 :(得分:3)
假设""
是NA
和'否'作为分组变量
library(dplyr)
df %>%
group_by(No.) %>%
mutate(Type = if(all(is.na(Req_No.))) NA else "A")
如果是空白(""
)而不是NA
df %>%
group_by(No.) %>%
mutate(Type = if(all(Req_No.=="")) "" else "A")
# A tibble: 6 x 4
# Groups: No. [3]
# No. Sub_No. Req_No. Type
# <int> <int> <chr> <chr>
#1 130 1 231 A
#2 130 2 "" A
#3 130 3 "" A
#4 121 1 "" ""
#5 140 1 398 A
#6 140 2 "" A
df <- structure(list(No. = c(130L, 130L, 130L, 121L, 140L, 140L), Sub_No. = c(1L,
2L, 3L, 1L, 1L, 2L), Req_No. = c(231L, NA, NA, NA, 398L, NA)), .Names = c("No.",
"Sub_No.", "Req_No."), class = "data.frame", row.names = c(NA,
-6L))
#df with blanks
df <- structure(list(No. = c(130L, 130L, 130L, 121L, 140L, 140L), Sub_No. = c(1L,
2L, 3L, 1L, 1L, 2L), Req_No. = c("231", "", "", "", "398", ""
)), .Names = c("No.", "Sub_No.", "Req_No."), row.names = c(NA,
-6L), class = "data.frame")