Как вызвать Dataframe и найти nrow в функции, используя R? - PullRequest
0 голосов
/ 30 сентября 2018

Мой вопрос немного сложен.У меня есть вектор, как показано ниже

vec <-c("Camera","Battery","Protection")

И у меня есть фреймы данных, как показано ниже. Camera_pos # Фрейм данных, в котором есть несколько столбцов (здесь мы можем игнорировать детали).Точно так же у нас есть другие фреймы данных, такие как Camera_neg, Battery_pos, Battery_neg, Protection_pos, Protection_neg

Итак, у меня есть 6 фреймов данных, которые содержат некоторые наблюдения, и эти детали не представляют интереса для вопроса.

Я пытаюсь создать новый Dataframe, который извлекает данные / значения из вектора и фреймов данных.

df <- data.frame(Features = character(),Positive = numeric(), Negative = numeric()) # empty data frame
for(i in 1:length(vec)){
 df$Features[i] = vec[i] # Camera in case of vec[1]
 df$Positive[i] = nrow() # not sure what code to write here, but this code should call the nrow() of Camera_pos ( i =1 is considered here)
df$Negative[i] = nrow() # not sure what code to write here, but this code should call the nrow() of Camera_neg
}

Код должен быть примерно таким nrow(vec[i]_pos), то есть nrow(Camera_pos) в случае i = 1.Просим вас любезно помочь в этом

PS: Точно так же функция должна иметь возможность вызывать элементы и в другом векторе, чтобы в df было 3 строки и 3 столбца, заполненных

Выходные данные должны быть такими:ниже

Features        Positive         Negative
Camera          3                3
Battery         3                3
Protection      3                3

Ответы [ 2 ]

0 голосов
/ 30 сентября 2018

Вот подход tidyverse

Camera_pos <- data.frame(Text = c("text1","text2","text3"), Score = c(1.45,6.78,6.879))
Camera_neg <- data.frame(Text = c("text1","text2","text3"), Score = c(-0.5,-1.8,-1.4))
Battery_pos <- data.frame(Text = c("text1","text2","text3"), Score = c(0.5,1.8,1.4))
Battery_neg <- data.frame(Text = c("text1","text2","text3"), Score = c(-0.5,-1.8,-1.4))
Protection_pos <- data.frame(Text = c("text1","text2","text3"), Score = c(0.5,1.8,1.4))
Protection_neg <- data.frame(Text = c("text1","text2","text3"), Score = c(-0.5,-1.8,-1.4))

vec <-c("Camera","Battery","Protection")

library(tidyverse)

# get all your environment objetcs
obj_names = ls()

# function the returns the names of your workspace objects that match a pattern
f = function(x) data.frame(x, obj_names = obj_names[grepl(x, obj_names)], stringsAsFactors = F)

map_df(vec, ~f(.x)) %>%                       # apply the function to each pattern
  mutate(d = map(obj_names, ~get(.x))) %>%    # get the datasets
  unnest() %>%                                # unnest data
  mutate(type = ifelse(Score > 0, "Positive", "Negative")) %>%  # get the type of each score
  count(x, type) %>%                          # count combinations
  spread(type, n)                             # reshape

# # A tibble: 3 x 3
#   x          Negative Positive
#   <chr>         <int>    <int>
# 1 Battery           3        3
# 2 Camera            3        3
# 3 Protection        3        3
0 голосов
/ 30 сентября 2018

Это был бы способ сделать это:

#This would name all the files you have in your working directory
files <- ls()

library(stringr)

df <- data.frame(Features = rep(NA, length(vec)),Positive = rep(NA, length(vec)), Negative = rep(NA, length(vec))) # empty data frame

for(i in 1:length(vec)){
  df$Features[i] = vec[i] # Camera in case of vec[1]
  #Get a temp with only the name of vec[i] of your data.frame
  temp <- files[str_detect(files, vec[i])]
  df$Positive[i] = nrow(get(temp[str_detect(temp, "pos")])) # not sure what code to write here, but this code should call the nrow() of Camera_pos ( i =1 is considered here)
  df$Negative[i] = nrow(get(temp[str_detect(temp, "neg")])) # not sure what code to write here, but this code should call the nrow() of Camera_neg
}

Я мог бы объяснить более подробно, если есть что-то, что вы не понимаете

...