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
710 views
in Technique[技术] by (71.8m points)

r - To find the difference between two column elements in a data frame

My question is a very basic one and I am new to R and programming. I have a data frame RESULT with two columns Max, Min and 500 rows. I just want to find the difference between Max and Min and put the value in a third column Difference. I tried with the code:

select Max, Min, Max-Min as Difference from RESULT.

But I am getting

Error: unexpected symbol in "select Max".

I also tried just with:

Difference<-c(RESULT$Max-RESULT$Min) 

for which I am getting:

Warning Message

In Ops.factor(RESULT$Max, RESULT$Min) : - not meaningful for factors

RESULT:

    Max Min
1   NaN NaN
2   25  NaN
3   NaN NaN
4   NaN NaN
5   NaN NaN
6   25.6   23.1

I want to display NaN or any other variable like X or Y in Difference column whenever there is NaN in Either of Max or Min. The output should be like:

    Max Min   Difference
1   NaN NaN   NaN
2   25  NaN   NaN
3   NaN NaN   NaN
4   NaN 34    NaN
5   NaN NaN   NaN
6   25.6   23.1   2.5
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If df is your data.frame, df$V3 <- df$V1 - df$V2 should add a new column called V3 which is the difference of columns V1 and V2.

Your error message says that the columns are factors. You can convert them to a numeric class by doing df$V1 <- as.numeric(as.character(df$V1)) and similarly for V2


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

...