2015-09-01 34 views
0

使用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看這個?

非常感謝。

+0

目前尚不清楚。也許檢查'?merge'或'?match' – akrun

+0

或者查看如何提供一個可重複的例子。 – Heroka

+0

不是很清楚你想要什麼。您有一些與「exp_life」值關聯的年齡段(而不是年齡值)。您希望能夠將年齡值鏈接到「exp_life」值?如:年齡值7屬於年齡範圍6-10,因此它與exp_life值75.38相關聯? – AntoniosK

回答

2

使用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 
-1

這是使用包dplyrtidyr以產生有一個「年齡範圍」級別信息和「時代價值」級別的新的數據集的過程:

# 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 
+1

這不是一個好的解決方案,因爲當你需要做的只是檢查間隔時,你創建了一個不必要的大查找表。表格中不需要「所有可能的年齡值」。此外,這種查找方法不適用於分數年齡(10.5等)。 – C8H10N4O2

+0

我同意「findInterval」在不需要查找表的情況下使它更通用和更好。我錯誤地認爲年齡值是整數,因此查找表並不是一個大問題,因爲它不會有很多行。 – AntoniosK