If Statements Comparing DataFrames in R
2
0
Entering edit mode
2.7 years ago
jmw730 • 0

I need help altering this if else statement. I am trying to make a loop that will compare the lengths of DerpSubsetN and DerpSubsetT. Each time the loop is ran there will be different lengths tested against each other. My ultimate goal is to say if one is larger, it is cut to the length of the shorter one. This is being done in the programming language R.

For example,

Start with:

DerpSubsetT length = *47*
DerpSubesetN length =*59*

End with:

DerpSubsetT length = *47*
DerpSubesetN length =*47*

> `if(length(DerpSubsetN)>length(DerpSubsetT))
{
  length(DerpSubsetN)==length(DerpSubsetT)
}`

^This code above just returns a FALSE statement. How do you set it equal to the shorter length?

if-else loops R • 455 views
ADD COMMENT
2
Entering edit mode
2.7 years ago

This is basic R and therefore generally off topic on biostars. Anyway, I think you can benefit from following some R tutorials.

The following:

length(DerpSubsetN)==length(DerpSubsetT)

Is a comparison of the lengthvalues and therefore returns true or false.

What you are looking for is an assignment:

length(DerpSubsetN) = length(DerpSubsetT)
ADD COMMENT
2
Entering edit mode

We should add that

  • using loops in R is rarely a good idea, use apply, lapply, sapply etc.
  • one can only set the lengths of vector or list objects, which results in a truncated vector, trying this with something else results in an error
ADD REPLY
1
Entering edit mode

.. but a data.frame is a list, so this is valid

ADD REPLY
2
Entering edit mode
2.7 years ago
zx8754 10k

It is not very clear what we are trying to achieve, see example below:

# example data frames
x1 <- mtcars[1:2, 1:3]
x2 <- mtcars[3:4, 5:8]

Check the length (by the way we could instead use ncol()):

length(x1)
# [1] 3
length(x2)
# [1] 4

By changing the length of a data.frame to a smaller value, we are dropping the last column and data.frame class, result is a list:

length(x2) <- length(x1)
x2
# $drat
# [1] 3.85 3.08
# 
# $wt
# [1] 2.320 3.215
# 
# $qsec
# [1] 18.61 19.44

We could convert it back to data.frame:

x2 <- data.frame(x2)
x2
#   drat    wt  qsec
# 1 3.85 2.320 18.61
# 2 3.08 3.215 19.44
ADD COMMENT

Login before adding your answer.

Traffic: 1279 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6