简体   繁体   English

r- dummyVars中的重复行

[英]r- Duplicated rows in dummyVars

I have a dataframe in R, here there is an example 我在R中有一个数据框,这里有一个例子

asdf <- data.frame(id = c(2345, 7323, 2345, 4533),
               place = c("Home", "Home", "Office", "Office"),
               sex = c("Male", "Male", "Male", "Female"),
               consumed = c(1000, 800, 1000, 500))

As you can see there is one id duplicated, because he has two locations, Home and Office. 如您所见,有一个ID重复了,因为他有两个位置,分别是家庭和办公室。 I want to convert every character variable to a dummy variable, and obtain just one id, without duplicated id's. 我想将每个字符变量转换为一个虚拟变量,并仅获取一个id,而没有重复的id。 I am sure that the only duplicated values can be the "place" variable. 我确信唯一重复的值可以是“位置”变量。

When i apply dummyVars from caret, i can't do this, and for me this behavior does not make sense, for example, when I apply the following 当我从插入符中应用dummyVars时,我无法执行此操作,例如,当我应用以下命令时,这种行为就没有意义

dummy <- dummyVars( ~ ., data = asdf, fullRank = FALSE, levelsOnly = TRUE)
predict(dummy, asdf)

I get the following dataframe, with duplicated id's 我得到以下具有重复ID的数据框

result <- data.frame(id = c(2345, 7323, 2345, 4533),
                 placeHome = c(1, 1, 0, 0),
                 placeOffice = c(0, 0, 1, 1),
                 sexFemale = c(0, 0, 0, 1),
                 sexMale = c(1, 1, 1, 0),
                 consumed = c(1000,  800, 1000,  500))

but I want this 但是我想要这个

sexy_result <- data.frame(id = c(2345, 7323, 4533),
                 placeHome = c(1, 1, 0),
                 placeOffice = c(1, 0, 1),
                 sexFemale = c(0, 0, 1),
                 sexMale = c(1, 1, 0),
                 consumed = c(1000,  800, 500))

You could transform your result data frame using dplyr package. 您可以使用dplyr包来转换结果数据框。

library(dplyr)
sexy_result <- result %>% group_by(id) %>% summarise_all(sum)
data.frame(sexy_result)

   id    placeHome  placeOffice sexFemale sexMale consumed
1 2345         1           1         0       2     2000
2 4533         0           1         1       0      500
3 7323         1           0         0       1      800

If you want to sum only placeHome and placeOffice , you could use the following code 如果只想对placeHomeplaceOffice求和 ,则可以使用以下代码

sexy_result <- result %>% group_by(id) %>% summarise(placeHome=sum(placeHome), placeOffice=sum(placeOffice), sexFemale=mean(sexFemale), sexMale=mean(sexMale), consumed=mean(consumed))
data.frame(sexy_result)

   id     placeHome  placeOffice sexFemale sexMale consumed
1 2345         1           1         0       1     1000
2 4533         0           1         1       0      500
3 7323         1           0         0       1      800

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM