简体   繁体   中英

Access R Dataframe Values Rather than Tibble

I'm an experienced Pandas user and am having trouble plugging values from my R frame into a function.

The following function works with hard coded values

>seq.Date(as.Date('2018-01-01'), as.Date('2018-01-31'), 'days') 

 [1] "2018-01-01" "2018-01-02" "2018-01-03" "2018-01-04" "2018-01-05" "2018-01-06" "2018-01-07"
 [8] "2018-01-08" "2018-01-09" "2018-01-10" "2018-01-11" "2018-01-12" "2018-01-13" "2018-01-14"
[15] "2018-01-15" "2018-01-16" "2018-01-17" "2018-01-18" "2018-01-19" "2018-01-20" "2018-01-21"
[22] "2018-01-22" "2018-01-23" "2018-01-24" "2018-01-25" "2018-01-26" "2018-01-27" "2018-01-28"
[29] "2018-01-29" "2018-01-30" "2018-01-31"

Here is an extract from a dataframe I'm using

>df[1,1:2]
# A tibble: 1 x 2
  start_time end_time  
  <date>     <date>    
1 2017-04-27 2017-05-11

When plugging these values into the 'seq.Date' function I get an error

> seq.Date(from=df[1,1], to=df[1,2], 'days')
Error in seq.Date(from = df[1, 1], to = df[1, 2], "days") : 
'from' must be a "Date" object

I suspect this is because subsetting using df[x,y] returns a tibble rather than the specific value

data.class(df[1,1])
[1] "tbl_df"

What I'm hoping to derive is a sequence of dates. I need to be able to point this at various places around the dataframe.

Many thanks for any help!

只需使用双括号:

seq.Date(from=df[[1,1]], to=df[[1,2]], 'days')

tibble的提取函数可能不会返回向量而是一列反复,使用dplyr::pull将列提取为向量,就像在这个答案中一样: 将dplyr tbl列提取为向量

Another option is to set the drop argument in the `[` function to TRUE .

If TRUE the result is coerced to the lowest possible dimension

seq.Date(from = df[1, 1, drop = TRUE], to = df[1, 2, drop = TRUE], 'days')
# [1] "2017-04-27" "2017-04-28" "2017-04-29" "2017-04-30" "2017-05-01" "2017-05-02" "2017-05-03" "2017-05-04" "2017-05-05" "2017-05-06"
#[11] "2017-05-07" "2017-05-08" "2017-05-09" "2017-05-10" "2017-05-11"

data

df <- tibble(start_time = as.Date('2017-04-27'), 
             end_time = as.Date('2017-05-11'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM