使用R我基於分佈組合計算年齡。然後,這個年齡段的被鏈接到其在表中列出(或任何最方便的方法是)這樣的centrain預期壽命:R:用間隔列表中的值替換值
age exp_life
0-5 80
6-10 75.38
11-15 70.4
16-20 65.41
21-25 60.44
26-30 etc..
因此,例如,年齡7對應於75.38,我怎麼輕易方案在R看這個?
非常感謝。
使用R我基於分佈組合計算年齡。然後,這個年齡段的被鏈接到其在表中列出(或任何最方便的方法是)這樣的centrain預期壽命:R:用間隔列表中的值替換值
age exp_life
0-5 80
6-10 75.38
11-15 70.4
16-20 65.41
21-25 60.44
26-30 etc..
因此,例如,年齡7對應於75.38,我怎麼輕易方案在R看這個?
非常感謝。
使用findInterval()
找到exp_life
對應於age
區間。
使用類似於上一個答案的設置(但不需要創建整個查找表 - 如果您的年齡輸入不是整數,則無論如何這都不起作用)。
df <- read.table(header=TRUE,
text="age exp_life
0-5 80
6-10 75.38
11-15 70.4
16-20 65.41
21-25 60.44
26-30 etc..",
stringsAsFactors =FALSE)
library(tidyr); library(dplyr)
df %>%
separate(age, into=c('from_age','to_age'), sep='-') %>%
mutate_each(funs(as.numeric)) %>%
arrange(from_age) -> df # in case it's not sorted
df$exp_life[findInterval(7, df$from_age)] # returns [1] 75.38
這是使用包dplyr
和tidyr
以產生有一個「年齡範圍」級別信息和「時代價值」級別的新的數據集的過程:
# example dataset
dt = read.table(text=
"age exp_life
0-5 80
6-10 75.38
11-15 70.4
16-20 65.41
21-25 60.44", header=T)
library(tidyr)
library(dplyr)
dt %>%
separate(age, c("low","high")) %>% # split your range values into low and high
mutate(low = as.numeric(low), # make those columns numeric
high = as.numeric(high)) %>%
rowwise() %>% # for each row
do(data.frame(.,
age_val=seq(.$low,.$high,1))) %>% # get all possible age values and combine them with ranges and exp_life values
ungroup
# low high exp_life age_val
# 1 0 5 80.00 0
# 2 0 5 80.00 1
# 3 0 5 80.00 2
# 4 0 5 80.00 3
# 5 0 5 80.00 4
# 6 0 5 80.00 5
# 7 6 10 75.38 6
# 8 6 10 75.38 7
# 9 6 10 75.38 8
# 10 6 10 75.38 9
# 11 6 10 75.38 10
# 12 11 15 70.40 11
# 13 11 15 70.40 12
# 14 11 15 70.40 13
# 15 11 15 70.40 14
# 16 11 15 70.40 15
# 17 16 20 65.41 16
# 18 16 20 65.41 17
# 19 16 20 65.41 18
# 20 16 20 65.41 19
# 21 16 20 65.41 20
# 22 21 25 60.44 21
# 23 21 25 60.44 22
# 24 21 25 60.44 23
# 25 21 25 60.44 24
# 26 21 25 60.44 25
目前尚不清楚。也許檢查'?merge'或'?match' – akrun
或者查看如何提供一個可重複的例子。 – Heroka
不是很清楚你想要什麼。您有一些與「exp_life」值關聯的年齡段(而不是年齡值)。您希望能夠將年齡值鏈接到「exp_life」值?如:年齡值7屬於年齡範圍6-10,因此它與exp_life值75.38相關聯? – AntoniosK