2

Here is my problem with R:

I have a table similar to this:

TABLE_NAME          COLUM_NAME          DATA_TYPE 
table_1               DATA              DATE
table_1               NAME              VARCHAR2
table_1               SURNAME           VARCHAR2
table_2               DATA              DATE
table_2               PACK              NUMBER

what i want to do is to create 2 different table from this based on the TABLE_NAME value that will have TABLE_NAME as name. Like this

table_1

COLUM_NAME          DATA_TYPE 
   DATA              DATE
   NAME              VARCHAR2
   SURNAME           VARCHAR2

table_2

COLUM_NAME          DATA_TYPE
DATA              DATE
PACK              NUMBER

This way i can create a catalog of my tables, synonym and view of my db (with ROracle is not possible to fetch such metadata from the connection).

How can i Achieve this?

4

3 回答 3

3

We can use split to create a list of data.frames

lst1 <- split(df1[-1], df1[[1]])
lst1
#$table_1
#  COLUM_NAME DATA_TYPE
#1       DATA      DATE
#2       NAME  VARCHAR2
#3    SURNAME  VARCHAR2

#$table_2
#  COLUM_NAME DATA_TYPE
#4       DATA      DATE
#5       PACK    NUMBER

Here, split is splitting the data.frame based on the factor provided (f in split). It looks for rows that have the same elements in 'TABLE_NAME' and group them together and return a list of those similar rows

于 2019-03-19T14:29:47.007 回答
1

tidyverse你可以filter,他们使用删除第一列select

table1 <- df %>%
  filter(TABLE_NAME == "table_1") %>% 
  select(-TABLE_NAME)

table2 <- df %>%
  filter(TABLE_NAME == "table_2") %>% 
  select(-TABLE_NAME)

您还可以放置一个函数来处理大量数据帧:

table_fun <- function(x) {
  df %>%
    filter(TABLE_NAME == x) %>%
    select(-TABLE_NAME)
}

table_2 <- table_fun("table_2")

# A tibble: 2 x 2
  COLUM_NAME DATA_TYPE
  <chr>      <chr>    
1 DATA       DATE     
2 PACK       NUMBER 
于 2019-03-19T14:34:01.983 回答
1

dplyr你也可以试试:

df %>%
 group_split(TABLE_NAME)

[[1]]
# A tibble: 3 x 3
  TABLE_NAME COLUM_NAME DATA_TYPE
  <chr>      <chr>      <chr>    
1 table_1    DATA       DATE     
2 table_1    NAME       VARCHAR2 
3 table_1    SURNAME    VARCHAR2 

[[2]]
# A tibble: 2 x 3
  TABLE_NAME COLUM_NAME DATA_TYPE
  <chr>      <chr>      <chr>    
1 table_2    DATA       DATE     
2 table_2    PACK       NUMBER 
于 2019-03-19T14:39:24.500 回答