Subsetting data frame by factor level

百般思念 提交于 2019-12-22 08:34:29

问题


I have a big data frame with state names in one colum and different indexes in the other columns. I want to subset by state and create an object suitable for minimization of the index or a data frame with the calculation already given.

Here's one simple (short) example of what I have

m
  x   y
1 A 1.0
2 A 2.0
3 A 1.5
4 B 3.0
5 B 3.5
6 C 7.0

I want to get this

m
  x y
1 A 1.0
2 B 3.0
3 C 7.0

I don't know if a function with a for loop is necessary. Like

minimize<-function(x,...)
for (i in m$x){ 
do something with data by factor value 
apply to that something the min function in every column
return(y)
} 

so when you call

minimize(A)
[1] 1

I tried to use %in% but didn't work (I got this error).

A%in%m Error in match(x, table, nomatch = 0L) : object 'A' not found

When I define it it goes like this.

A<-c("A")
"A"%in%m
[1] FALSE

Thank you in advance


回答1:


Try aggregate:

aggregate(y ~ x, m, min)

  x y
1 A 1
2 B 3
3 C 7



回答2:


Use aggregate

> aggregate(.~x, FUN=min, dat)
  x y
1 A 1
2 B 3
3 C 7

See this post to get some other alternatives.




回答3:


Using data.table

require(data.table)
m <- data.table(m)

m[, j=min(y), by=x]
#    x V1
# 1: A  1
# 2: B  3
# 3: C  7


来源:https://stackoverflow.com/questions/21266887/subsetting-data-frame-by-factor-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!