Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

r - Sum object in a column between an interval defined by another column

I have a data frame like this:

  df
       A B
 [1,]  1 4
 [2,]  2 3
 [3,]  3 5
 [4,]  4 7
 [5,]  5 5
 [6,]  6 7
 [7,]  7 4
 [8,]  8 7
 [9,]  9 3
[10,] 10 7

I need to sum the numbers in column B that fall between a certain interval defined by column A. For example sum the value in B between A≥1 and A<3.

I'm trying to use this:

> sum(which(df$B[df$A>=1] & df$B[df$A<3]))

but it does not give me what I want.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're almost there.

with(my.df, sum(my.df[A >= 1 & A < 3, "B"]))

EDIT

Chase challenged me to explain away the code at hand. When reading R code, it's best to read from inwards out. Here we go.

my.df is a data.frame (think Excel sheet) with columns A and B. Square brackets [] are used to subset anything from this object like so: [rows, columns]. For example, [1, ] would return the entire first row, and if you add a column number (or column name), you get value in first row in that column (e.g. [1, 2], where you would get value in the first row of the second column). We will now subset rows in my.df with A >= 1 & A < 3. What we're saying here is we want to see those rows that have values in A bigger or equal to 1 and smaller than 3. This will give us all rows that satisfy this criterion. If we add , "B" it means we want to select column B. Since we already subsetted the result to contain only rows that fit the above criterion, by entering column name B we get values only in the column. Once you have those values from column B you sum them using sum(). Use of with function is there to make our life easier. If we hadn't used that, we would be forced to call columns by their full name my.df$A and my.df$B.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...