jeudi 28 janvier 2021

Why is my R dataframe not being copied in ifelse statement?

I have a dataframe tas_i with 875000 rows as below:

    head(tas_i)

  x tas year month_no
1 1  NA 1884        1
2 2  NA 1884        1
3 3  NA 1884        1
4 4  NA 1884        1
5 5  NA 1884        1
6 6  NA 1884        1

I have a relatively simple ifelse statement that just doesn't work (see below). What am I doing wrong? My object tas ends up being a 'list' of numbers and not a 'dataframe'.

> i
[1] 1
> j
[1] 1884
> tas <- ifelse(i==1 & j==1884, tas_i, rbind(tas,tas_i))
> nrow(tas_i)
[1] 875000
> nrow(tas)
NULL
> tas_i[1:6,]
  x tas year month_no
1 1  NA 1884        1
2 2  NA 1884        1
3 3  NA 1884        1
4 4  NA 1884        1
5 5  NA 1884        1
6 6  NA 1884        1
> tas[1:6,]
Error in tas[1:6, ] : incorrect number of dimensions
class(tas)
[1] "list"
> class(tas_i)
[1] "data.frame"

Note that if I perform tas <- tas_i, it works fine and tas is a dataframe

tas <- tas_i
class(tas)
[1] "data.frame"

emphasized text

Aucun commentaire:

Enregistrer un commentaire