Reputation: 854
I have the following data frame structure:
Animal Food
1 cat fish, milk, shrimp
2 dog steak, poo
3 fish seaweed, shrimp, krill, insects
I would like to reorganize it so that the rows are in descending order of number of factors in the "Food" column:
Animal Food
1 fish seaweed, shrimp, krill, insects
2 cat fish, milk, shrimp
3 dog steak, poo
Is there an R function that can help me with that? Thanks
Upvotes: 0
Views: 266
Reputation: 2526
You can order the frame according to the results of your counting function:
animals = data.frame( rbind(c("cat","fish, milk, shrimp"),
c("dog","steak, poo"),
c("fish","seaweed, shrimp, krill, insects")))
colnames(animals) = c("Animal","Food")
animals[order(sapply(animals$Food, function(x) { length(strsplit(as.character(x),split=",")[[1]]) })), ]
I put in the as.character
because it defaults to a factor, you probably don't need it (quicker) alternatively you can use stringsAsFactors=FALSE
when creating the data frame.
Upvotes: 1
Reputation: 3711
make a new variable and sort by that, edit: thanks to Ananda and alexis
df$nFood<-length(unlist(strsplit(df$Food, ",", fixed=T)))
df$nFood<-sapply(strsplit(df$Food, ","), length)
Upvotes: 1
Reputation: 193517
You can use count.fields
to figure out how many items there are in each "food" row and order by that.
count.fields(textConnection(mydf$Food), ",")
# [1] 3 2 4
Assuming your data.frame
is called "mydf":
mydf[order(count.fields(textConnection(mydf$Food), ","), decreasing=TRUE),]
# Animal Food
# 3 fish seaweed, shrimp, krill, insects
# 1 cat fish, milk, shrimp
# 2 dog steak, poo
Upvotes: 4