当我对通过下面的代码生成的起始数据帧myDF
运行自定义函数runLabel()
时,我得到以下输出。该代码生成两个数据帧:Label
和selGrpCode
,并且Label
需要由selGrpCode
中的值进行操作,从而在Label
数据帧中添加(变异(新的matchOnes
列。但是matchOnes
列没有出现在Label
数据帧中。
> runLabel(myDF)
Element Group eleCnt eleGrpCnt grpPrefix subGrpRnk grpCode
1 R 0 1 0 0 0 0.0
2 R 0 2 0 0 0 0.0
3 B 0 1 0 0 0 0.0
4 R 0 3 0 0 0 0.0
5 X 1 1 1 1 1 1.1
6 X 1 2 1 2 2 2.2
grpCode
1 1.1
2 2.2
library(dplyr)
myDF <- data.frame(
Element = c("R","R","B","R","X","X"),
Group = c(0,0,0,0,1,1)
)
runLabel <- function(x) {Label <- x %>%
group_by(Element) %>%
mutate(eleCnt = row_number()) %>%
mutate(eleGrpCnt = ifelse(Group != 0,match(Group, unique(Group)),0)) %>%
ungroup() %>%
mutate(grpPrefix = eleCnt * eleGrpCnt) %>%
mutate(subGrpRnk = ifelse(Group > 0, sapply(1:n(), function(x) sum(Element[1:x]==Element[x] & Group[1:x] == Group[x])),0)) %>%
mutate(grpCode = as.numeric(paste(grpPrefix,subGrpRnk, sep = '.')))
selGrpCode <- Label %>% distinct(grpCode) %>% select(grpCode) %>% filter(grpCode > 0) %>% arrange(grpCode)
Label %>% mutate(matchOnes = ifelse(eleCnt < min(selGrpCode),eleCnt,0))
print.data.frame(Label)
print.data.frame(selGrpCode)
}
这就是Label
数据帧的显示方式(将缺失的列添加到右侧(:
Element Group eleCnt eleGrpCnt grpPrefix subGrpRnk grpCode matchOnes
1 R 0 1 0 0 0 0.0 1
2 R 0 2 0 0 0 0.0 0
3 B 0 1 0 0 0 0.0 1
4 R 0 3 0 0 0 0.0 0
5 X 1 1 1 1 1 1.1 1
6 X 1 2 1 2 2 2.2 0
如何调整函数以使两个数据帧可以运行和交互?尽可能使用dplyr。请不要将其简化为一个数据帧,因为此代码是对更多相关代码的简化,需要运行两个数据帧。
您必须在末尾保存Label
变量,否则不会从您的函数中打印突变:
runLabel <- function(x) {
...
Label <- Label %>% mutate(matchOnes = ifelse(eleCnt < min(selGrpCode),eleCnt,0))
...
}
这里是你的完整代码:
library(dplyr)
myDF <- data.frame(
Element = c("R","R","B","R","X","X"),
Group = c(0,0,0,0,1,1)
)
runLabel <- function(x) {
Label <- x %>%
group_by(Element) %>%
mutate(eleCnt = row_number()) %>%
mutate(eleGrpCnt = ifelse(Group != 0,match(Group, unique(Group)),0)) %>%
ungroup() %>%
mutate(grpPrefix = eleCnt * eleGrpCnt) %>%
mutate(subGrpRnk = ifelse(Group > 0, sapply(1:n(), function(x) sum(Element[1:x]==Element[x] & Group[1:x] == Group[x])),0)) %>%
mutate(grpCode = as.numeric(paste(grpPrefix,subGrpRnk, sep = '.')))
selGrpCode <- Label %>% distinct(grpCode) %>% select(grpCode) %>% filter(grpCode > 0) %>% arrange(grpCode)
Label <- Label %>% mutate(matchOnes = ifelse(eleCnt < min(selGrpCode),eleCnt,0))
print.data.frame(Label)
print.data.frame(selGrpCode)
}
runLabel(myDF)
#> Element Group eleCnt eleGrpCnt grpPrefix subGrpRnk grpCode matchOnes
#> 1 R 0 1 0 0 0 0.0 1
#> 2 R 0 2 0 0 0 0.0 0
#> 3 B 0 1 0 0 0 0.0 1
#> 4 R 0 3 0 0 0 0.0 0
#> 5 X 1 1 1 1 1 1.1 1
#> 6 X 1 2 1 2 2 2.2 0
#> grpCode
#> 1 1.1
#> 2 2.2
创建于2022-09-12,reprex v2.0.2