如何使用R中的函数有条件地对数据帧进行子集设置



我有一个数据帧,看起来像这样:

a b
1 1
2 2
3 3
4 4
5 5

您可以使用一堆if/else:

f <- function(n, data){
if(n == 1){
data.frame(a = head(data[1], n), 
b = head(data[2], n)) |>
transform(result = a + b)
}
else{
if(n == nrow(data)) n <- 1
data.frame(a = head(data[1], n), 
b = tail(data[2], n)) |>
transform(result = a + b)
}
}

输出

lapply(vec, f, data = w)
[[1]]
a b result
1 1 1      2
[[2]]
a b result
1 1 4      5
2 2 5      7
[[3]]
a b result
1 1 3      4
2 2 4      6
3 3 5      8
[[4]]
a b result
1 1 2      3
2 2 3      5
3 3 4      7
4 4 5      9
[[5]]
a b result
1 1 5      6

您可以使用ifelse函数,它对我来说总是比ifelse指令更简单。试试这个它会起作用:

library(tidyverse)
a = seq(1,5,1)
b = seq(1,5,1)
w = tibble(a,b)
im = function(mat,window){


SA = unlist(#unlist to transform list type result of ifelse to vector
ifelse(
# here is the condition
window==nrow(mat),
# if condition is TRUE return first element
mat%>%
dplyr::select(1)%>%
dplyr::slice_head(n=1),
# if condition is FALSE return first window elements
mat%>%
dplyr::select(1)%>%
dplyr::slice_head(n=window))

)

SB = unlist(
ifelse(window==nrow(mat),
mat%>%
dplyr::select(2)%>%
dplyr::slice_tail(n=1),
mat%>%
dplyr::select(2)%>%
dplyr::slice_tail(n=window))
)

margin = min(SA+SB)

return(margin)
}

im(w,5)

最新更新