Thiyagu
Thiyagu

Reputation: 111

comparing an element in a column in a data frame with another element in the same column in another data frame for corresponding rows in R

I am new to programming and obviously new to R. I am learning some documents in R and started programming in R.

I have four data frames with data frame names Data1, Data2, Data3, Data4. Each data frames has eight columns (V1, V2, V3, V4, V5, V6, V7, V8) and 10,000 rows.The number of rows and number of columns is same for all the data frames.

I want to compare the elements of each row's 8th column (V8) of all the four data frame with each other with their corresponding rows and find the maximum and minimum value. For example if I have 10 rows and 8 columns in each data frame, I have to compare the 1st row 8th column element of Data1, Data2, Data3, Data4 to find the maximum and minimum value. Then i have to compare the 2nd row 8th column element of Data1, Data2, Data3, Data4 to find the maximum and minimum value. Similary the 3rd row 8th column element, 4th row 8th column element and i have to do this for remaining 10,000 rows. How should I do this and what function should I use?

Upvotes: 0

Views: 283

Answers (2)

flodel
flodel

Reputation: 89057

Sample data:

Data1 <- as.data.frame(matrix(runif(80), 10, 8))
Data2 <- as.data.frame(matrix(runif(80), 10, 8))
Data3 <- as.data.frame(matrix(runif(80), 10, 8))
Data4 <- as.data.frame(matrix(runif(80), 10, 8))

You can do:

pmin(Data1$V8, Data2$V8, Data3$V8, Data4$V8)
pmax(Data1$V8, Data2$V8, Data3$V8, Data4$V8)

Or something more programmatic (there can be many variations here)

Datas <- mget(paste0("Data", 1:4))
do.call(pmin, lapply(Datas, `[[`, "V8"))
do.call(pmax, lapply(Datas, `[[`, "V8"))

Upvotes: 2

Sophia
Sophia

Reputation: 1951

You could combine your columns in a new dataframe. Then its easy to find the row-wise min or max values:

newd <- data.frame(a=Data1$V8, b=Data2$V8, c=Data3$V8, d=Data4$V8)
apply(newd, 1, max)

Upvotes: 1

Related Questions