6
考慮一個簡單的例子:與mutate_at創建新的變量,同時保持原有的
library(dplyr)
dataframe <- data_frame(helloo = c(1,2,3,4,5,6),
ooooHH = c(1,1,1,2,2,2),
ahaaa = c(200,400,120,300,100,100))
# A tibble: 6 x 3
helloo ooooHH ahaaa
<dbl> <dbl> <dbl>
1 1 1 200
2 2 1 400
3 3 1 120
4 4 2 300
5 5 2 100
6 6 2 100
在這裏,我想給函數ntile
應用於包含oo
的所有列,但我想這些新列是稱爲cat
+對應的列。
我知道我能做到這一點
dataframe %>% mutate_at(vars(contains('oo')), .funs = funs(ntile(., 2)))
# A tibble: 6 x 3
helloo ooooHH ahaaa
<int> <int> <dbl>
1 1 1 200
2 1 1 400
3 1 1 120
4 2 2 300
5 2 2 100
6 2 2 100
但我需要的是這個
# A tibble: 8 x 5
helloo ooooHH ahaaa cat_helloo cat_ooooHH
<dbl> <dbl> <dbl> <int> <int>
1 1 1 200 1 1
2 2 1 400 1 1
3 3 1 120 1 1
4 4 2 300 2 2
5 5 2 100 2 2
6 5 2 100 2 2
7 6 2 100 2 2
8 6 2 100 2 2
是否有不需要存儲中間數據,併合並回原來的解決方案數據幀?
我想我總是可以寫一些正則表達式的東西來改變'col_cat'變量的名字? –
@ℕʘʘḆḽḘ。爲方便起見,可能在'rename_at'中;在編輯中添加示例。 – aosmith
如果有多個列包含匹配項,則重命名似乎只能附加。 有沒有辦法讓它追加一場比賽呢? 例如:'dataframe%>%mutate_at(vars(contains('ah')),.funs = funs(cat = ntile(。,2)))' – bheavner