dat <- data.frame(loc = c(1,2), year = c(1980,2012), id1 = c(5,6), id2 = c(10,12), id3 = c(14,18),id4 = c(10,12))
dat
loc year id1 id2 id3 id4
1 1 1980 5 10 14 10
2 2 2012 6 12 18 12
对于每一行,我想将id1
添加到id4
,将其除以100,然后将此id1
乘以id4
。我做了第一部分。如何在一个函数中完成第二部分?
dat$factor <- apply(dat[,3:6], 1, function(x) 100/sum(x))
如何在上面的相同函数中将因子和id2除以因子?
答案 0 :(得分:4)
您还可以使用直接索引(而不是使用apply
):
cols <- c("id1", "id2", "id3", "id4");
dat[cols] <- dat[cols] * 100 / rowSums(dat[cols]);
# loc year id1 id2 id3 id4
#1 1 1980 12.82051 25.64103 35.89744 25.64103
#2 2 2012 12.50000 25.00000 37.50000 25.00000
答案 1 :(得分:2)
以下是tidyverse
library(tidyverse)
dat %>%
select(matches("id")) %>%
reduce(`+`) %>%
mutate(dat, new = .) %>%
mutate_at(vars(matches("id")), funs(100*./new)) %>%
select(-new)
# loc year id1 id2 id3 id4
#1 1 1980 12.82051 25.64103 35.89744 25.64103
#2 2 2012 12.50000 25.00000 37.50000 25.00000
或gather/spread
dat %>%
gather(key, val, id1:id4) %>%
group_by(loc, year) %>%
mutate(val = 100* val/sum(val)) %>%
spread(key, val)
# A tibble: 2 x 6
# Groups: loc, year [2]
# loc year id1 id2 id3 id4
#* <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 1.00 1980 12.8 25.6 35.9 25.6
#2 2.00 2012 12.5 25.0 37.5 25.0