如何解决如何使用R根据列中其他单元格中的信息将信息添加到单元格?
我的数据帧看起来很乱
df <- data.frame(Job = c("casual","part time","full time","Level A total","casual","Level B total"),institute1 = c(1,2,5,1,1))
“ B级总计”上方的行指的是B级,直到行升至“ A级总计”,现在它指的是A级。数据的长度大于500行,因此手动清洁一个选项,但是不愉快,但是我想不起来如何编写代码,所以我可以添加信息,以便R知道每个单元格所指的级别。
解决方法
我们可以创建一个新列Level
并将所有"Level"
值放入其中。 fill
个NA
值,其下的非NA值。通过添加来自Level
的文本来清理Job
列。
library(dplyr)
df %>%
mutate(Level = replace(Job,!grepl('Level',Job),NA)) %>%
tidyr::fill(Level,.direction = 'up') %>%
mutate(Level = ifelse(grepl('total',Job,paste0(sub('total','',Level),Job)))
# Job institute1 Level
#1 casual 1 Level A casual
#2 part time 2 Level A part time
#3 full time 2 Level A full time
#4 Level A total 5 Level A total
#5 casual 0 Level B casual
#6 full time 1 Level B full time
#7 Level B total 1 Level B total
,
Base R解决方案:
transform(within(df[rev(seq_len(nrow(df))),],{
Level <- ifelse(grepl("Level\\s*[A-Z]",gsub("\\s*total","",NA_character_)
}
),Level = na.omit(Level)[cumsum(!(is.na(Level)))])[rev(seq_len(nrow(df))),]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。