[英]How to delete first level of headers of a Dataframe in R?
I created a data frame from an aggregate - function. 我从聚合函数创建了一个数据框。 The length of the data-frame is two. 数据帧的长度为两个。 However when I print the data-frame out 5 columns appear. 但是,当我打印出数据框时,会出现5列。 How does R handle headers and sub headers in a data frame? R如何处理数据帧中的标头和子标头? How can I get rid of the first level of headers if this is the case here? 如果是这种情况,我如何摆脱头文件的第一级?
d <- data.frame("User id"=c(1,1,2,3,1),
block=c("north","south","east","west","south"), check.names = F)
f <- function(l, vec) {
vec[l] <- 1
vec
}
vec <- setNames(rep(0, 4), levels(d$block))
df <- aggregate(block~`User id`, d, f, vec)
These are the outputs that confuse me: 这些输出使我感到困惑:
>names(df)
[1] "User id" "block"
> df
User id block.east block.north block.south block.west
1 1 0 1 1 0
2 2 1 0 0 0
3 3 0 0 0 1
This is what I want to have: 这就是我想要的:
> names(df)
> "User id" "block.east" "block.north" "block.south" "block.west"
We can do this more easily with table
我们可以用table
更轻松地做到这一点
out <- as.data.frame.matrix(+(table(d) > 0))
names(df) <- paste0("block.", names(df))
Regarding the issue in OP's output, it is a matrix
column, 关于OP输出中的问题,它是一个matrix
列,
str(df)
#'data.frame': 3 obs. of 2 variables:
# $ User id: num 1 2 3
# $ block : num [1:3, 1:4] 0 1 0 1 0 0 1 0 0 0 ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : NULL
# .. ..$ : chr "east" "north" "south" "west"
so we can convert to regular data.frame with 因此我们可以将其转换为常规data.frame
df <- do.call(data.frame, df)
names(df)
#[1] "User.id" "block.east" "block.north" "block.south" "block.west"
str(df)
#'data.frame': 3 obs. of 5 variables:
# $ User.id : num 1 2 3
# $ block.east : num 0 1 0
# $ block.north: num 1 0 0
# $ block.south: num 1 0 0
# $ block.west : num 0 0 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.