-2

I have got a list of numbers, with attribute names. It is a stock ticker dataset where in each numeric value reflects how many times the ticker occurs in my dataset. So given that

data <- c(0, 12, 15, 6)
names(data) <- c("SZC", "MSFT", "AAPL", "GOOG")

such that

data[["AAPL"]]

15

I want to get the attribute name as another variable in my dataframe rather than an attribute. I have tried

data %>%
(mutate(names = names(data)))

which gives me an error saying Error in UseMethod("mutate") :

no applicable method for 'mutate' applied to an object of class "character"

How do I separate name attributes from a vector and get it as a variable in my dataframe?

2 Answers2

1

How to figure out what went wrong.

From ?mutate:

   .data: A data frame, data frame extension (e.g. a tibble), or a lazy
          data frame (e.g. from dbplyr or dtplyr). See _Methods_,
          below, for more details.

This says that the input data (the LHS when used with %>%, i.e., the data object here) must be a data.frame or frame-like.

You have a couple of easy options when starting with a vector:

library(dplyr)

### using @nicola's `stack` suggestion
stack(data)
#   values  ind
# 1      0  SZC
# 2     12 MSFT
# 3     15 AAPL
# 4      6 GOOG

### same, but renaming
stack(data) %>%
  rename(names = ind, data = values)
#   data names
# 1    0   SZC
# 2   12  MSFT
# 3   15  AAPL
# 4    6  GOOG

Another:

tibble(data) %>%
  mutate(names = names(data))
# # A tibble: 4 x 2
#    data names
#   <dbl> <chr>
# 1     0 SZC  
# 2    12 MSFT 
# 3    15 AAPL 
# 4     6 GOOG 
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • Thanks this is of great help! I have a question if you don't mind, I was looking at stack() documentation and it says *concatenates multiple vectors into a single vector along with a factor indicating where each observation originated.* How and why does() stack return the attributes as a column then? –  May 12 '21 at 15:19
  • The names are required (try it without the names), that is the point: to take the data and its attributes and convert into a long-form frame. It does things a little differently for a `data.frame`, which is what I think the first paragraph is geared towards. I don't know that I have a better answer for you other than *this is what it does for vectors*, sorry. – r2evans May 12 '21 at 15:27
0

Is this what you want??

data <- c(0, 12, 15, 6)
names(data) <- c("SZC", "MSFT", "AAPL", "GOOG")
#a dataframe with 2 cols and rownames
df <- data.frame(name=names(data),value=data)
#a dataframe with 2 cols and without rownames
df <- data.frame(name=names(data),value=unname(data))
Elia
  • 2,210
  • 1
  • 6
  • 18