logo

R – Frame di dati

Linguaggio di programmazione R è un linguaggio di programmazione open source ampiamente utilizzato come software statistico e strumento di analisi dei dati. Frame di dati in linguaggio R sono oggetti dati generici di R utilizzati per archiviare dati tabulari.

I frame di dati possono anche essere interpretati come matrici in cui ciascuna colonna di a matrice possono essere di diversi tipi di dati. R DataFrame è costituito da tre componenti principali, dati, righe e colonne.



Struttura dei frame di dati R

Come puoi vedere nell'immagine qui sotto, ecco come è strutturato un frame di dati.

I dati sono presentati in forma tabellare, che ne facilita il funzionamento e la comprensione.

R - Frame di datiGeeksforgeeks

R – Frame di dati



Creare Dataframe nel linguaggio di programmazione R

Per creare un frame di dati R utilizzare dati.frame() funzione e quindi passa ciascuno dei vettori che hai creato come argomenti alla funzione.

R






# R program to create dataframe> # creating a data frame> friend.data <->data.frame>(> >friend_id =>c>(1:5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,> >'Dravid'>,>'Sehwag'>,> >'Dhoni'>),> >stringsAsFactors =>FALSE> )> # print the data frame> print>(friend.data)>

>

>

Produzione:

 friend_id friend_name 1 1 Sachin 2 2 Sourav 3 3 Dravid 4 4 Sehwag 5 5 Dhoni>

Ottieni la struttura del frame di dati R

È possibile ottenere la struttura del frame di dati R utilizzando str() funzione in R.

Può visualizzare anche la struttura interna di elenchi di grandi dimensioni nidificati. Fornisce un output di una riga per gli oggetti R di base che consentono all'utente di conoscere l'oggetto e i suoi componenti.

R




numero intero rispetto a Java

# R program to get the> # structure of the data frame> # creating a data frame> friend.data <->data.frame>(> >friend_id =>c>(1:5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,> >'Dravid'>,>'Sehwag'>,> >'Dhoni'>),> >stringsAsFactors =>FALSE> )> # using str()> print>(>str>(friend.data))>

>

>

Produzione:

'data.frame': 5 obs. of 2 variables:  $ friend_id : int 1 2 3 4 5  $ friend_name: chr 'Sachin' 'Sourav' 'Dravid' 'Sehwag' ... NULL>

Riepilogo dei dati nel frame dati R

Nel frame dati R, il riepilogo statistico e la natura dei dati possono essere ottenuti mediante l'applicazione riepilogo() funzione.

Si tratta di una funzione generica utilizzata per produrre riepiloghi dei risultati di varie funzioni di adattamento del modello. La funzione invoca metodi particolari che dipendono dalla classe del primo argomento.

R




# R program to get the> # summary of the data frame> # creating a data frame> friend.data <->data.frame>(> >friend_id =>c>(1:5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,> >'Dravid'>,>'Sehwag'>,> >'Dhoni'>),> >stringsAsFactors =>FALSE> )> # using summary()> print>(>summary>(friend.data))>

>

>

Produzione:

 friend_id friend_name   Min. :1 Length:5   1st Qu.:2 Class :character   Median :3 Mode :character   Mean :3   3rd Qu.:4   Max. :5>

Estrai i dati dal frame di dati in R

Estrarre dati da un data frame R significa accedere alle sue righe o colonne. È possibile estrarre una colonna specifica da un frame di dati R utilizzando il nome della colonna.

R




# R program to extract> # data from the data frame> # creating a data frame> friend.data <->data.frame>(> >friend_id =>c>(1:5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,> >'Dravid'>,>'Sehwag'>,> >'Dhoni'>),> >stringsAsFactors =>FALSE> )> # Extracting friend_name column> result <->data.frame>(friend.data$friend_name)> print>(result)>

>

>

Produzione:

 friend.data.friend_name 1 Sachin 2 Sourav 3 Dravid 4 Sehwag 5 Dhoni>

Espandi frame dati in linguaggio R

Un frame di dati in R può essere espanso aggiungendo nuove colonne e righe al frame di dati R già esistente.

R




# R program to expand> # the data frame> # creating a data frame> friend.data <->data.frame>(> >friend_id =>c>(1:5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,> >'Dravid'>,>'Sehwag'>,> >'Dhoni'>),> >stringsAsFactors =>FALSE> )> # Expanding data frame> friend.data$location <->c>(>'Kolkata'>,>'Delhi'>,> >'Bangalore'>,>'Hyderabad'>,> >'Chennai'>)> resultant <- friend.data> # print the modified data frame> print>(resultant)>

>

>

Produzione:

stringa in char java
 friend_id friend_name location 1 1 Sachin Kolkata 2 2 Sourav Delhi 3 3 Dravid Bangalore 4 4 Sehwag Hyderabad 5 5 Dhoni Chennai>

In R, è possibile eseguire vari tipi di operazioni su un frame di dati come accedere a righe e colonne, selezionare il sottoinsieme del frame di dati, modificare frame di dati, eliminare righe e colonne in un frame di dati , eccetera.

Per favore riferisci a Operazioni DataFrame in R conoscere tutti i tipi di operazioni che possono essere eseguite su un frame di dati.

Accedere agli elementi nel frame dati R

Possiamo selezionare e accedere a qualsiasi elemento dal data frame utilizzando single$>,parentesi[ ] or>doppie parentesi[[]]>per accedere alle colonne da un frame di dati.

R




# creating a data frame> friend.data <->data.frame>(> >friend_id =>c>(1:5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,> >'Dravid'>,>'Sehwag'>,> >'Dhoni'>),> >stringsAsFactors =>FALSE> )> # Access Items using []> friend.data[1]> # Access Items using [[]]> friend.data[[>'friend_name'>]]> # Access Items using $> friend.data$friend_id>

>

>

Produzione:

 friend_id 1 1 2 2 3 3 4 4 5 5 Access Items using [[]] [1] 'Sachin' 'Sourav' 'Dravid' 'Sehwag' 'Dhoni'   Access Items using $ [1] 1 2 3 4 5>

Quantità di righe e colonne

Possiamo scoprire quante righe e colonne sono presenti nel nostro dataframe utilizzando la funzione dim.

R




# creating a data frame> friend.data <->data.frame>(> >friend_id =>c>(1:5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,> >'Dravid'>,>'Sehwag'>,> >'Dhoni'>),> >stringsAsFactors =>FALSE> )> # find out the number of rows and clumns> dim>(friend.data)>

>

>

Produzione:

[1] 5 2>

Aggiungi righe e colonne nel frame dati R

Puoi aggiungere facilmente righe e colonne in un DataFrame R. L'inserimento aiuta ad espandere il DataFrame già esistente, senza averne bisogno di uno nuovo.

Diamo un'occhiata a come aggiungere righe e colonne in un DataFrame? con un esempio:

Aggiungi righe nel frame dati R

Per aggiungere righe in un Data Frame, puoi utilizzare una funzione integrata rbind().

L'esempio seguente dimostra il funzionamento di rbind() in R Data Frame.

R




elenco Java di

# Creating a dataframe representing products in a store> Products <->data.frame>(> >Product_ID =>c>(101, 102, 103),> >Product_Name =>c>(>'T-Shirt'>,>'Jeans'>,>'Shoes'>),> >Price =>c>(15.99, 29.99, 49.99),> >Stock =>c>(50, 30, 25)> )> # Print the existing dataframe> cat>(>'Existing dataframe (Products): '>)> print>(Products)> # Adding a new row for a new product> New_Product <->c>(104,>'Sunglasses'>, 39.99, 40)> Products <->rbind>(Products, New_Product)> # Print the updated dataframe after adding the new product> cat>(>' Updated dataframe after adding a new product: '>)> print>(Products)>

>

>

Produzione:

Existing dataframe (Products):   Product_ID Product_Name Price Stock 1 101 T-Shirt 15.99 50 2 102 Jeans 29.99 30 3 103 Shoes 49.99 25  Updated dataframe after adding a new product:   Product_ID Product_Name Price Stock 1 101 T-Shirt 15.99 50 2 102 Jeans 29.99 30 3 103 Shoes 49.99 25 4 104 Sunglasses 39.99 40>

Aggiungi colonne nel frame dati R

Per aggiungere colonne in un Data Frame, puoi utilizzare una funzione integrata cbind().

L'esempio seguente dimostra il funzionamento di cbind() in R Data Frame .

R




# Existing dataframe representing products in a store> Products <->data.frame>(> >Product_ID =>c>(101, 102, 103),> >Product_Name =>c>(>'T-Shirt'>,>'Jeans'>,>'Shoes'>),> >Price =>c>(15.99, 29.99, 49.99),> >Stock =>c>(50, 30, 25)> )> # Print the existing dataframe> cat>(>'Existing dataframe (Products): '>)> print>(Products)> # Adding a new column for 'Discount' to the dataframe> Discount <->c>(5, 10, 8)># New column values for discount> Products <->cbind>(Products, Discount)> # Rename the added column> colnames>(Products)[>ncol>(Products)] <->'Discount'> # Renaming the last column> # Print the updated dataframe after adding the new column> cat>(>' Updated dataframe after adding a new column 'Discount': '>)> print>(Products)>

>

>

Produzione:

Existing dataframe (Products):   Product_ID Product_Name Price Stock 1 101 T-Shirt 15.99 50 2 102 Jeans 29.99 30 3 103 Shoes 49.99 25  Updated dataframe after adding a new column 'Discount':   Product_ID Product_Name Price Stock Discount 1 101 T-Shirt 15.99 50 5 2 102 Jeans 29.99 30 10 3 103 Shoes 49.99 25 8>

Rimuovi righe e colonne

Un data frame in R rimuove colonne e righe dal data frame R già esistente.

Rimuovi riga in R DataFrame

R




library>(dplyr)> # Create a data frame> data <->data.frame>(> >friend_id =>c>(1, 2, 3, 4, 5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,>'Dravid'>,>'Sehwag'>,>'Dhoni'>),> >location =>c>(>'Kolkata'>,>'Delhi'>,>'Bangalore'>,>'Hyderabad'>,>'Chennai'>)> )> data> # Remove a row with friend_id = 3> data <->subset>(data, friend_id != 3)> data>

>

>

Produzione:

 friend_id friend_name location 1 1 Sachin Kolkata 2 2 Sourav Delhi 3 3 Dravid Bangalore 4 4 Sehwag Hyderabad 5 5 Dhoni Chennai   # Remove a row with friend_id = 3   friend_id friend_name location 1 1 Sachin Kolkata 2 2 Sourav Delhi 4 4 Sehwag Hyderabad 5 5 Dhoni Chennai>

Nel codice sopra, abbiamo prima creato un frame di dati chiamato dati con tre colonne: amico_id , nome_amico , E posizione . Per rimuovere una riga con amico_id uguale a 3, abbiamo utilizzato il sottoinsieme() funzione e specificata la condizione id_amico!= 3 . Ciò ha rimosso la riga con amico_id pari a 3.

Rimuovi colonna in R DataFrame

R




library>(dplyr)> # Create a data frame> data <->data.frame>(> >friend_id =>c>(1, 2, 3, 4, 5),> >friend_name =>c>(>'Sachin'>,>'Sourav'>,>'Dravid'>,>'Sehwag'>,>'Dhoni'>),> >location =>c>(>'Kolkata'>,>'Delhi'>,>'Bangalore'>,>'Hyderabad'>,>'Chennai'>)> )> data> # Remove the 'location' column> data <->select>(data, -location)> data>

>

>

Produzione:

come convertire una stringa in intero
 friend_id friend_name location 1 1 Sachin Kolkata 2 2 Sourav Delhi 3 3 Dravid Bangalore 4 4 Sehwag Hyderabad 5 5 Dhoni Chennai>Rimuovi la colonna 'località' friends_id friend_name 1 1 Sachin 2 2 Sourav 3 3 Dravid 4 4 Sehwag 5 5 Dhoni>

Per rimuovere il posizione colonna, abbiamo utilizzato la colonna Selezionare() funzione e specificata -posizione . IL il segno indica che vogliamo rimuovere il file posizione colonna. Il frame di dati risultante dati avrà solo due colonne: amico_id E nome_amico .

Combinazione di frame di dati in R

Esistono 2 modi per combinare i frame di dati in R. Puoi combinarli verticalmente o orizzontalmente.

Consideriamo entrambi i casi con un esempio:

Combina il frame dati R verticalmente

Se vuoi combinare 2 frame di dati verticalmente, puoi usare rbind() funzione. Questa funzione funziona per la combinazione di due o più frame di dati.

R




# Creating two sample dataframes> df1 <->data.frame>(> >Name =>c>(>'Alice'>,>'Bob'>),> >Age =>c>(25, 30),> >Score =>c>(80, 75)> )> df2 <->data.frame>(> >Name =>c>(>'Charlie'>,>'David'>),> >Age =>c>(28, 35),> >Score =>c>(90, 85)> )> # Print the existing dataframes> cat>(>'Dataframe 1: '>)> print>(df1)> cat>(>' Dataframe 2: '>)> print>(df2)> # Combining the dataframes using rbind()> combined_df <->rbind>(df1, df2)> # Print the combined dataframe> cat>(>' Combined Dataframe: '>)> print>(combined_df)>

>

>

Produzione:

Dataframe 1:   Name Age Score 1 Alice 25 80 2 Bob 30 75  Dataframe 2:   Name Age Score 1 Charlie 28 90 2 David 35 85  Combined Dataframe:   Name Age Score 1 Alice 25 80 2 Bob 30 75 3 Charlie 28 90 4 David 35 85>

Combina frame dati R orizzontalmente:

Se vuoi combinare 2 frame di dati orizzontalmente, puoi usare funzione cbind(). Questa funzione funziona per la combinazione di due o più frame di dati.

R




# Creating two sample dataframes> df1 <->data.frame>(> >Name =>c>(>'Alice'>,>'Bob'>),> >Age =>c>(25, 30),> >Score =>c>(80, 75)> )> df2 <->data.frame>(> >Height =>c>(160, 175),> >Weight =>c>(55, 70)> )> # Print the existing dataframes> cat>(>'Dataframe 1: '>)> print>(df1)> cat>(>' Dataframe 2: '>)> print>(df2)> # Combining the dataframes using cbind()> combined_df <->cbind>(df1, df2)> # Print the combined dataframe> cat>(>' Combined Dataframe: '>)> print>(combined_df)>

>

>

Produzione:

Dataframe 1:   Name Age Score 1 Alice 25 80 2 Bob 30 75  Dataframe 2:   Height Weight 1 160 55 2 175 70  Combined Dataframe:   Name Age Score Height Weight 1 Alice 25 80 160 55 2 Bob 30 75 175 70>

Leggi anche:

  • R – Oggetti
  • Strutture dati nella programmazione R

In questo articolo abbiamo trattato R frame di dati, e tutte le operazioni di base come creazione, accesso, riepilogo, aggiunta e rimozione. Questo articolo ha lo scopo di farti acquisire familiarità con i frame di dati in R in modo da poterlo utilizzare nei tuoi progetti.

Spero che questo ti aiuti a comprendere il concetto di frame di dati in R e che tu possa facilmente implementare il frame di dati R nei tuoi progetti.