我有一个如下所示的数据框:
project_counts <- read.table(
text = "Project Counts
'Old Patient' 4
'Old Customer' 2
'New Patient' 5
'Children' 3",
header=T)
我正在尝试创建一个名为&#34; Subject&#34;获取Count列并将其乘以2,基于匹配&#34; Project&#34;中的特定子字符串。柱。例如,如果Project有子串&#39; Old&#39;在其中我希望该行的主题列采用Count * 2,但如果它显示&#39; New&#39;我希望它取得Count * 4,但是如果它说'孩子&#39;我希望它采用Count * 5
我开始编写一个for循环,只是为了尝试使用&#39; Old&#39;子串,这是我得到的。似乎没有工作......
for (i in 1:length(project_counts$Project)) {
if (grep('Old', project_counts$Project[i])) {
project_counts$Subject <- project_counts$Counts*2
}
}
答案 0 :(得分:1)
看看ifelse声明。它可以用于检查连续的if-else场景,并将值分配给新列&#39; Subject&#39;。
project_counts <- tibble::tribble(~Project,~Counts,
'Old Patient', 4,
'Old Customer', 2,
'New Patient', 5,
'Children', 3)
project_counts['Subject'] <- ifelse(substr(project_counts[['Project']],1,3)=='Old',project_counts[['Counts']]*2,ifelse(substr(project_counts[['Project']],1,3)=='New',project_counts[['Counts']]*4,ifelse(substr(project_counts[['Project']],1,8)=='Children',project_counts[['Counts']]*5,0)))
答案 1 :(得分:1)
Project <- c('Old Patient',
'Old Customer',
'New Patient',
'Children')
Counts <- c(4, 2, 5, 3)
project_counts <- data.frame(Project, Counts, stringsAsFactors = F)
project_counts$Subject <- ifelse(grepl('Old', project_counts$Project),
project_counts$Counts * 2,
ifelse(grepl('New', project_counts$Project),
project_counts$Counts * 4,
project_counts$Counts * 5))
project_counts
## Project Counts Subject
## 1 Old Patient 4 8
## 2 Old Customer 2 4
## 3 New Patient 5 20
## 4 Children 3 15
答案 2 :(得分:1)
即使问题得到解答,我也试图提出一种更为通用的方法。看看
encapsulation: ViewEncapsulation.None
#
.angular-cli.json