Reputation: 883
I cannot figure out how to do this. I have a data.frame in R. It looks like this:
Scores <- read.table(text = "
ID Test1 Test2 Test3 Final
1 Student1 20 23 21 48
2 Student2 16 15 18 36
3 Student3 25 20 22 40
4 Student4 14 19 18 42
5 Student5 10 15 14 30
")
What I want is to create a new data object that has the range of values for each test, including the final. So it will look something like this:
result <- read.table(text = "
min max
Test1 10 25
Test2 15 23
Test3 14 22
Final 30 48
")
It honestly doesn't matter to me whether it just lists the max and min values, or actually calculate the difference. I just can't figure out a way to implement this that isn't unnecessarily complicated. I know I can pull the columns out manually and individually, but there must be some better way of doing this. Something involving by()
or tapply()
? But I just cannot get them to work.
Any ideas?
Upvotes: 2
Views: 27127
Reputation: 1
colrange<-function(x){
sapply(x,range)
}
Make a colrange
fucntion and insert your data: colrange(scores)
Upvotes: 0
Reputation: 1
(r_dd <- range(rdu_flights[5])), here rdu_flights is my data frame, [5] is the index number (you can find by using names("rdu_flights"), r_dd is the variable I am calling the range. I think this is pretty simple. I got the result as [1] -17 293 # represents the min and max values for departure delay of certain flights
Upvotes: 0
Reputation: 15458
Another approach:
kk<-Map(function(x) cbind(x,min=min(Scores[,x]),max=max(Scores[,x])), as.list(names(Scores)[-1]))
data.frame(do.call(rbind,kk))
x min max
1 Test1 10 25
2 Test2 15 23
3 Test3 14 22
4 Final 30 48
Upvotes: 0
Reputation: 7794
set.seed(1)
scores <- data.frame(ID=paste0("Student",1:5),
T1=sample(100,5),
T2=sample(100,5),
T3=sample(100,5),
Final=sample(100,5))
summ <- data.frame(min=apply(scores[,!grepl("ID",colnames(scores))],2,min),
max=apply(scores[,!grepl("ID",colnames(scores))],2,max))
> summ
min max
T1 20 89
T2 6 94
T3 18 74
Final 37 98
Upvotes: 0
Reputation: 17432
A bit simpler:
> t(sapply(test, range))
[,1] [,2]
a 1 3
b 2 5
d 1 2
Upvotes: 10
Reputation: 28274
Try this, reproducible example included.
test <- data.frame(a=c(1,2,3),b=c(2,3,5),d=c(1,2,2))
data.frame(min=sapply(test,min),max=sapply(test,max))
EDIT: Adding to @Blue Magister request for reproducible example: Look into ?dput
?structure
to figure out how to post your data.frame
here, e.g: dput(scores).
Upvotes: 1